如何强制此Nodejs功能等到Fs.WriteFile完成?
我根据这些说明正在实现https.request()除非做一个stdout,否则我写的是文件。我希望结束等到文件编写过程完成。我该怎么做?
process.stdout.write(d);
将其更改为
fs.writeFile(path, d, err => {
if (err) {
console.error(err);
} else {
console.log("data => " path)
}
})
整个代码
const https = require('node:https');
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
更新
MTN发布了一种有效的解决方案,但我意识到我的代码稍微复杂得多。我以块读取该文件,然后在最后保存。 MTN的解决方案很早完成。这是代码。谁能帮我修复它?
const request = https.request(url, (response, error) => {
if (error) {console.log(error)}
let data = '';
response.on('data', (chunk) => {
data = data + chunk.toString();
});
response.on('end', () => {
fs.writeFile(path, data, err => {
if (err) {
console.error(err);
} else {
console.log("data => " path)
}
})
})
})
request.on('error', (error) => {
console.error(error);
})
request.end()
},
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
直接的答案是,在您的
console.log
之后,编写文件后应该发生的任何事情都必须进入回调。 (不过,您的代码中没有任何东西可以在之后运行。)但是:
您的代码会更简单。
使用库发送HTTP请求而不是RAW
> https 模块。 (例如:
got
,axios
,node -fetch
,...) - 不仅要照顾诸如阅读身体之类的事情对于您来说,它们也有一个承诺接口,使您可以执行第2点。重写代码以使用
async
/等待
。。
这是一个示例,
got
:注意: ES6模块是因为我使用了顶级
等待
和import
,而got
甚至不再支持commonj。因此,要么您的package.json
必须具有“ type”:“ module”
,要么必须是mjs
。The immediate answer would be that whatever should happen after the file was written would have to go into the callback, after your
console.log
. (There is nothing in your code that looks like it's supposed to run afterwards though.)But:
Your code would be a lot simpler if you'd...
Use a library for sending HTTP requests instead of the raw
https
module. (For example:got
,axios
,node-fetch
, ...) - Not only do these take care of things like reading the body for you, they also have a promise interface which allows you to do point 2.Rewrite the code to uses
async
/await
.Here is an example with
got
:Note: This has to be an ES6 module because I used top-level
await
andimport
, andgot
doesn't even support CommonJS anymore. So either yourpackage.json
would have to have"type": "module"
or the file ending would have to bemjs
.您可以改用
fs.writefilesync()
。它的同步,因此等待写作完成You can use
fs.writeFileSync()
instead. Its sync so it waits for the writing to be finished在fs.writefile中,在最后一个回调函数中添加您想做的任何事情。
Inside the fs.writeFile, add whatever you want to do in the last callback function.