cURL equivalent in Node.js?
you can easily use request module:
https://www.npmjs.com/package/request
Sample code:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
else {
console.log("Error "+response.statusCode)
}
})
The http
module that you use to run servers is also used to make remote requests.
Here's the example in their docs:
var http = require("http");
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
See the documentation for the HTTP module for a full example:
https://nodejs.org/api/http.html#http_http_request_options_callback
Since looks like node-curl
is dead, I've forked it, renamed, and modified to be more curl like and to compile under Windows.
node-libcurl
Usage example:
var Curl = require( 'node-libcurl' ).Curl;
var curl = new Curl();
curl.setOpt( Curl.option.URL, 'www.google.com' );
curl.setOpt( 'FOLLOWLOCATION', true );
curl.on( 'end', function( statusCode, body, headers ) {
console.info( statusCode );
console.info( '---' );
console.info( body.length );
console.info( '---' );
console.info( headers );
console.info( '---' );
console.info( this.getInfo( Curl.info.TOTAL_TIME ) );
this.close();
});
curl.on( 'error', function( err, curlErrorCode ) {
console.error( err.message );
console.error( '---' );
console.error( curlErrorCode );
this.close();
});
curl.perform();
Perform is async, and there is no way to use it synchronous currently (and probably will never have).
It's still in alpha, but this is going to change soon, and help is appreciated.
Now it's possible to use Easy
handle directly for sync requests, example:
var Easy = require( 'node-libcurl' ).Easy,
Curl = require( 'node-libcurl' ).Curl,
url = process.argv[2] || 'http://www.google.com',
ret, ch;
ch = new Easy();
ch.setOpt( Curl.option.URL, url );
ch.setOpt( Curl.option.HEADERFUNCTION, function( buf, size, nmemb ) {
console.log( buf );
return size * nmemb;
});
ch.setOpt( Curl.option.WRITEFUNCTION, function( buf, size, nmemb ) {
console.log( arguments );
return size * nmemb;
});
// this call is sync!
ret = ch.perform();
ch.close();
console.log( ret, ret == Curl.code.CURLE_OK, Easy.strError( ret ) );
Also, the project is stable now!