尝试使用 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中使用相对路径时,它们与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");
});
对我来说,问题是给定的文件名包含 Windows 上不允许的字符。
具体来说,我尝试在名称中添加时间戳,例如不允许
10:23:11
和 :
导致此错误。
就我而言,我试图将文件写入不存在的路径中。因此,请确保创建要在其中写入的文件夹。