【问题标题】:ENOENT error when using fs.writeFile使用 fs.writeFile 时出现 ENOENT 错误
【发布时间】:2015-04-19 20:59:27
【问题描述】:

尝试使用 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


【解决方案1】:

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

具体来说,我尝试在名称中添加时间戳,例如不允许使用 10:23:11: 导致此错误。

【讨论】:

    【解决方案2】:

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

    在您的情况下,您可以使用__dirname 全局变量,它返回as the docs say

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

    所以你的代码应该是这样的:

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

    【讨论】:

    • 我建议使用 process.chdir() 将应用的工作目录更改为 __dirname(或者更有用的路径,例如使用 asar)。这将允许您使用相对路径而无需大惊小怪。
    • 当我尝试使用path.join('abc', '.', 'pdf') 生成fileName 时遇到此错误,该'/''.' 字符之前和之后放置了一个'/'。希望此评论对某人有所帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    相关资源
    最近更新 更多