admin管理员组文章数量:1429061
I have the following code:
let request = require('request');
let fs = require('fs');
request.get('http://localhost:8080/report.rtf')
.pipe(fs.createWriteStream(__dirname + '/savedDoc.rtf'));
It works well, but only if the document is successfully downloaded from the given URL. However, if there is any HTTP: 403, 404 or any other error, an empty file is saved with zero length!
How can I .pipe()
this only in case of HTTP: 200 response without using any additional HEAD requests? It should be possible to do in one go!
I have the following code:
let request = require('request');
let fs = require('fs');
request.get('http://localhost:8080/report.rtf')
.pipe(fs.createWriteStream(__dirname + '/savedDoc.rtf'));
It works well, but only if the document is successfully downloaded from the given URL. However, if there is any HTTP: 403, 404 or any other error, an empty file is saved with zero length!
How can I .pipe()
this only in case of HTTP: 200 response without using any additional HEAD requests? It should be possible to do in one go!
1 Answer
Reset to default 7Check .statusCode
before piping:
const req = request
.get('http://localhost:8080/report.rtf')
.on('response', function (res) {
if (res.statusCode === 200) {
req.pipe(fs.createWriteStream(__dirname + '/savedDoc.rtf'))
}
})
本文标签: javascriptHow to pipe() npmrequest only if HTTP 200 is receivedStack Overflow
版权声明:本文标题:javascript - How to pipe() npm-request only if HTTP 200 is received? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745465770a2659529.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论