📜  如何在 javascript 代码示例中运行 curl

📅  最后修改于: 2022-03-11 15:02:33.095000             🧑  作者: Mango

代码示例1
#Since javascript already has functions for this purpose
#so it is not advisable to load an extra library for that
#you can achieve the same in native javascript like this
var url = "http://www.google.com";

var xhr = new XMLHttpRequest();
xhr.open("GET", url);

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
   }};

xhr.send();

#But still if you want to do it using curl in Node.js, it is possible
#Take a look at: https://github.com/JCMais/node-libcurl
var Curl = require( 'node-libcurl' ).Curl;

var curl = new Curl();

curl.setOpt( 'URL', 'http://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( this.getInfo( 'TOTAL_TIME' ) );

    this.close();
});

curl.on( 'error', function ( err, errCode ) {

    //do something

    this.close();
});

curl.perform();