【问题标题】:Can't find the file I created by fs.writeFile找不到我由 fs.writeFile 创建的文件
【发布时间】:2020-02-01 12:05:57
【问题描述】:

我正在尝试使用 fs.writeFile 在 node.js 中写入文件,我使用以下代码:

 const fs = require('filer');
 const jsonString = JSON.stringify(myObj)
       fs.writeFile('/myFile.txt', jsonString, function (err) {
        if (err) throw err;
        console.log('Saved!');
      });
    }

我确定该文件已创建,因为我可以通过 fs.readFile 引用相同的地址读取它,但我无法使用 windows 搜索在磁盘上找到它。我的理解是,如果我更改本地主机端口,它会将文件保存在另一个位置。我已经尝试过“process.cwd()”,但没有成功。

如果有人能提供帮助,我真的很感激。

【问题讨论】:

    标签: node.js writefile file-location


    【解决方案1】:

    尝试使用:__dirname 而不是 process.cwd()

    const fs = require('fs');
    const path = require('path');
    const filePath = path.join(__dirname, '/myFile.txt');
    console.log(filePath);
    const jsonString = JSON.stringify({ name: "kalo" })
    fs.writeFile(filePath, jsonString, (err) => {
        if (err) throw err;
        console.log('The file has been saved!');
    });
    
    

    我想知道你为什么使用“文件管理器”而不是默认的 fs 模块?

    fs 模块是在 node js 中提供文件处理的本机模块。所以你不需要专门安装它。此代码完美运行,它也打印文件的绝对位置。如果它不起作用,请运行此代码,我认为您应该重新安装 node js。我已经更新了答案。您也可以使用 fs.writeFileSync 方法。

    【讨论】:

    • 我使用了“filer”,因为根据npmjs.com/package/fs,“fs”似乎不再存在。我也试过 __dirname 但它返回“/myFile.txt”。
    【解决方案2】:

    来自文档:“String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as determined by calling process.cwd().

    因此,为了确定您的工作目录(即 fs 默认创建文件的位置)调用(适用于我):

    console.log(process.cwd());
    

    如果你想改变你的工作目录,你可以打电话(也适用于我):

    process.chdir('path_to_new_directory');
    

    路径可以是相对的或绝对的。

    这也来自文档:“The process.chdir() method changes the current working directory of the Node.js process or throws an exception if doing so fails (for instance, if the specified directory does not exist)。”

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 2017-12-21
      • 2019-10-03
      • 2020-01-04
      • 2020-03-03
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多