You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu Server上如何让PM2拥有创建文件夹权限?

问题:Express文件上传目录创建失败(PM2管理)

问题场景

在Ubuntu Server上部署了一个用PM2管理的Express应用,其中一个接口通过以下代码接收并保存文件:

fs.access(path.join(__dirname, '..', 'static', 'images', 'users', userId), (error) => {
  if (error) {
    fs.mkdirSync(path.join(__dirname, '..', 'static', 'images', 'users', userId));
  }
});

错误日志

进程崩溃后,PM2日志输出如下:

0|App | node:internal/fs/utils:344
0|App |     throw err;
0|App |     ^
0|App |
0|App | Error: ENOENT: no such file or directory, mkdir '/var/www/services.my-app.it/static/images/users/Vtk7xRzSU0fmaqyViTbv5ItQTXs2'
0|App |     at Object.mkdirSync (node:fs:1334:3)
0|App |     at /var/www/services.my-app.it/dist/index.js:1:11558
0|App |     at FSReqCallback.oncomplete (node:fs:188:23) {
0|App |   errno: -2,
0|App |   syscall: 'mkdir',
0|App |   code: 'ENOENT',
0|App |   path: '/var/www/services.my-app.it/static/images/users/Vtk7xRzSU0fmaqyViTbv5ItQTXs2'
0|App | }
0|App | error Command failed with exit code 1.

当前目录权限

执行ll命令得到的目录权限信息:

▶ ll
total 312K
drwxr-xr-x   2 root  root  4.0K May  4 12:15 dist
-rw-rw-r--   1 thefe thefe 1.1K May  2 15:18 index.js
-rw-rw-r--   1 thefe thefe  440 May  2 14:55 jsconfig.json
drwxrwxr-x 485 thefe thefe  20K May  2 14:56 node_modules
-rw-rw-r--   1 thefe thefe 1.4K May  2 14:55 package.json
-rw-rw-r--   1 thefe thefe 2.3K Apr 15  2022 service-account.json
drwxrwxr-x   7 thefe thefe 4.0K Apr  9 19:59 src
drwxrwxrwx   2 root  root  4.0K May  4 09:48 static
-rw-rw-r--   1 thefe thefe 1012 May  2 14:55 webpack.config.js
-rw-rw-r--   1 thefe thefe 259K May  2 14:55 yarn.lock

排查与解决方案

  1. 错误根源:
    日志里的ENOENT不是单纯权限问题——你要创建的路径中,images和users目录可能根本不存在!默认的fs.mkdirSync只能创建最后一级目录,上级目录缺失就会报错。

  2. 代码修复:
    给mkdirSync加上{ recursive: true }参数,让它自动创建所有缺失的上级目录:

    fs.access(path.join(__dirname, '..', 'static', 'images', 'users', userId), (error) => {
      if (error) {
        fs.mkdirSync(path.join(__dirname, '..', 'static', 'images', 'users', userId), { recursive: true });
      }
    });
    

    也可以直接省略access判断(递归创建时若目录已存在不会报错):

    fs.mkdirSync(path.join(__dirname, '..', 'static', 'images', 'users', userId), { recursive: true });
    
  3. 权限配置补充:
    确保PM2运行用户对static目录有写入权限:

    • 查看PM2进程运行用户:执行pm2 show App,在status区域找到user字段
    • 如果运行用户是thefe,修改static目录所有者:
      sudo chown -R thefe:thefe /var/www/services.my-app.it/static
      
    • 或者给目录添加组写入权限(若PM2用户属于root组):
      sudo chmod -R g+w /var/www/services.my-app.it/static
      

内容的提问来源于stack exchange,提问作者Ale TheFe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 18:22:49