使用 fs.writeFile 时出现 ENOENT 错误

问题描述 投票:0回答:3

尝试使用 fs.writeFile 将文件写入同级目录中。当在同一目录中使用

Sitemap.xml
时效果很好,但不适用于相对路径。
public
目录存在,无论
Sitemap.xml
是否存在,都会给出相同的错误。

相关目录结构:

/public
   Sitemap.xml
   app files
/create-sitemap
    index.js - file containing code below
app.js

fs.write('../public/Sitemap.xml', data.toString(), function(err) {
    if (err) throw err;
    console.log("Wrote sitemap to XML");
});


Toms-MacBook-Pro:moviehunter tomchambers$ node create-sitemap/index.js

/Users/tomchambers/projects/project/create-sitemap/index.js:88
        if (err) throw err;
                       ^
Error: ENOENT, open '../public/Sitemap.xml'
node.js fs
3个回答
34
投票

当你在node中使用相对路径时,它们与node进程相关。因此,如果您从

node create-sitemap/index.js
目录运行像
/Users/tomchambers/projects/project/
这样的脚本,它将查找不存在的
/Users/tomchambers/projects/public/Sitemap.xml
文件。

在你的情况下,你可以使用

__dirname
全局变量,它返回,正如文档所说

当前执行脚本所在目录的名称。

所以你的代码应该如下所示:

var path = require('path');

fs.write(path.join(__dirname, '../public/Sitemap.xml'), data.toString(), function(err) {
  if (err) throw err;
  console.log("Wrote sitemap to XML");
});

10
投票

对我来说,问题是给定的文件名包含 Windows 上不允许的字符。

具体来说,我尝试在名称中添加时间戳,例如不允许

10:23:11
:
导致此错误。


0
投票

就我而言,我试图将文件写入不存在的路径中。因此,请确保创建要在其中写入的文件夹。

© www.soinside.com 2019 - 2024. All rights reserved.