使用fs.writeFile时出现ENOENT错误

Tom*_*Tom 13 fs node.js

尝试使用fs.writeFile将文件写入兄弟目录.这在使用Sitemap.xml到同一目录时工作正常,但不能与相对路径一起使用.该public目录存在,无论是否存在,它都会给出相同的错误Sitemap.xml.

相关目录结构:

/public
   Sitemap.xml
   app files
/create-sitemap
    index.js - file containing code below
app.js
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)

Rod*_*ros 21

在节点中使用相对路径时,它们与节点进程相关.因此,如果您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");
});
Run Code Online (Sandbox Code Playgroud)


Ice*_*nge 10

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

具体来说,我尝试向名称添加时间戳,例如10:23:11,但:不允许添加时间戳,这导致了此错误。