I'm trying to leverage the node-request module, but the documentation isn't that great. If I make a request to a valid resource and pipe it to a Writable Stream, everything works fine. However, if I make a request to an invalid object, the Writable Stream is still created. Example, take the following snippet:
var x = request("http://localhost:3000/foo.jpg"); var st = fs.createWriteStream("foo.jpg"); x.pipe(st);
If the foo.jpg resource exists on the server, the data is piped to the stream, and it creates the file fine on the server. However, if foo.jpg does not exist on the server, a blank container file is still created. There appears to be no error event or anything that can be leveraged to determine if the request returned a 404. I've tried something like the following:
var x = request("http://localhost:3000/foo.jpg", function(err, response, body) { if(response.statusCode === 200) { // Success var st = fs.createWriteStream("foo.jpg"); x.pipe(st); } });
And also:
request("http://localhost:3000/foo.jpg", function(err, response, body) { if(response.statusCode === 200) { // Success var x = response.request; var st = fs.createWriteStream("foo.jpg"); x.pipe(st); } });
To no avail. The idea is pretty simple; I just want to copy a file identified by the URL to the local server. If the request is invalid (404, etc), don't pipe the file; if the request is valid, pipe the file. Any suggestions?
How NodeJS handle multiple client requests? NodeJS receives multiple client requests and places them into EventQueue. NodeJS is built with the concept of event-driven architecture. NodeJS has its own EventLoop which is an infinite loop that receives requests and processes them.
Request isn't really deprecated. It's no longer considering new features or breaking changes, but it is still being maintained. It's safe to use for the foreseeable future, but how good an idea it is to use it is up to the developer.
Request and Response object both are the callback function parameters and are used for Express. js and Node. js. You can get the request query, params, body, headers, and cookies. It can overwrite any value or anything there.
I wrote a request :)
you might want to try this
var r = request(url) r.on('response', function (resp) { resp.headers resp.statusCode r.pipe(new WritableStream()) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With