Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node-request - How to determine if an error occurred during the request?

Tags:

node.js

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?

like image 605
naivedeveloper Avatar asked Aug 28 '11 18:08

naivedeveloper


People also ask

How does node js handle concurrent requests?

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.

Is node request deprecated?

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.

What is request and response in node?

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.


1 Answers

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()) }) 
like image 115
mikeal Avatar answered Oct 03 '22 19:10

mikeal