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'))
}
})
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745465770a4628913.html
评论列表(0条)