前言
对于nodejs项目,打包应用有几种可选方式
- 本地install安装依赖后,连同node_modules目录一起打包到应用中
- 用pkg或者什么其它工具打包成可执行文件
- 在安装应用时install安装依赖
其它方式没什么问题,这里要说的是第三点,安装应用时安装依赖。
实例
以下是一个简单应用代码,依赖express
app/server/index.js 代码
const express = require('express');
const app = express();
app.get('/api/hello', (req, res) => {
res.json('Hello World');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
cmd/install_callback 安装回调脚本
#!/bin/bash
### This script is called after the user installs the application.
cd "${TRIM_APPDEST}/server"
"/var/apps/nodejs_v22/target/bin/node" "/var/apps/nodejs_v22/target/bin/npm" install
exit 0
问题
在实际fpk安装中,一直没能正确安装依赖,最后通过对install命令记录日志得到了一些信息,大概就是nodejs把/home 当作临时缓存目录,但是却没有目录权限
npm error code EACCES
npm error syscall mkdir
npm error path /home/apitest
npm error errno -13
npm error Error: EACCES: permission denied, mkdir '/home/apitest'
npm error at async Object.mkdir (node:internal/fs/promises:858:10)
npm error at async makeTmp (/vol1/@appcenter/nodejs_v22/lib/node_modules/npm/node_modules/cacache/lib/content/write.js:156:3)
npm error at async handleContent (/vol1/@appcenter/nodejs_v22/lib/node_modules/npm/node_modules/cacache/lib/content/write.js:103:15) {
npm error errno: -13,
npm error code: 'EACCES',
npm error syscall: 'mkdir',
npm error path: '/home/apitest'
npm error }
npm error
npm error The operation was rejected by your operating system.
npm error It is likely you do not have the permissions to access this file as the current user
npm error
npm error If you believe this might be a permissions issue, please double-check the
npm error permissions of the file and its containing directories, or try running
npm error the command again as root/Administrator.
npm notice
npm notice New major version of npm available! 10.9.3 -> 11.7.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v11.7.0
npm notice To update run: npm install -g npm@11.7.0
npm notice
npm error Log files were not written due to an error writing to the directory: /home/apitest/.npm/_logs
npm error You can rerun the command with `--loglevel=verbose` to see the logs in your terminal
解决
最后的解决办法有两种
1、更改缓存目录,比如更改到应用目录下
#!/bin/bash
### This script is called after the user installs the application.
cd "${TRIM_APPDEST}/server"
export npm_config_cache="${TRIM_APPDEST}/server/npm_cache"
mkdir -p $npm_config_cache
"/var/apps/nodejs_v22/target/bin/node" "/var/apps/nodejs_v22/target/bin/npm" install
exit 0
2、更改应用为root权限,也就是config/privilege
{
"username": "apitest",
"groupname": "apitest",
"defaults": {
"run-as": "root"
}
}