Node.js fs.readFile可以工作,但readFileSync返回空内容

Node.js fs.readFile可以工作,但readFileSync返回空内容,node.js,fs,Node.js,Fs,以下代码块将内容变量保留为空: 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: "ut

以下代码块将
内容
变量保留为空:

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读取文件,那么内容就是它应该的内容


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

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

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

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

您在代码中的什么位置使用
内容