【问题标题】:fs.readFile works, but readFileSync returns empty contentfs.readFile 有效,但 readFileSync 返回空内容
【发布时间】:2018-11-21 17:35:06
【问题描述】:

以下代码块将content 变量留空:

const file = fs.createWriteStream("/home/pi/rpi-main/descriptor.json");

http.get(url, function (response) {
    let content;

    response.pipe(file);
    content = fs.readFileSync("/home/pi/rpi-main/descriptor.json", { encoding: "utf-8" });
});

但是,如果我使用 fs.readFile 读取文件,内容就是它应有的内容。

为什么同步调用会发生这种情况?

【问题讨论】:

  • 您在代码中的哪个位置使用content

标签: node.js fs


【解决方案1】:

这是因为pipe 是一个异步函数,所以当你调用readFileSync 时它实际上还没有开始向文件写入任何内容。

您应该在管道的finish 事件的回调中读取您的文件。

response.pipe(file).on('finish', () => {
    content = fs.readFileSync(filename, { encoding: "utf-8" });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    相关资源
    最近更新 更多