使用fs.writeFile时ENOENT错误

尝试使用fs.writeFile将文件写入兄弟目录。 当将Sitemap.xml使用到相同的目录中时,这可以正常工作,但与相对path无关。 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' 

在节点中使用相对path时,它们与节点进程相关。 因此,如果您从/Users/tomchambers/projects/project/目录运行脚本,如node create-sitemap/index.js ,则会查找/Users/tomchambers/projects/public/Sitemap.xml文件不存在。

在你的情况下,你可以使用__dirname全局variables,返回, 如文档所说 :

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

所以你的代码应该看起来像这样:

 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"); });