cURL equivalent in Node.js?

后端 未结 18 600
误落风尘
误落风尘 2020-11-29 16:43

I\'m looking to use information from an HTTP request using Node.js (i.e. call a remote web service and echo the response to the client).

In PHP I would have used cUR

18条回答
  •  隐瞒了意图╮
    2020-11-29 16:55

    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!

提交回复
热议问题