Getting Started with node. JS-Accessing the outside world using HTTP

Source: Internet
Author: User

node. JS's HTTP module can be used not only to build servers, but also to access other servers as a client class library. The key is in two ways:

    • Http.request (Options[,callback])
    • Http.get (Path[,callback])

In addition to HTTP, the stream in the filesystem module and stream is used. Readable and stream.writable.

Let's start by introducing the relevant API.

API explanation

The Http.request () method accepts an options parameter, which can be an object that indicates the options associated with the network resource you want to access, such as hostname, path, port, method, and so on. The following is a simple option to download the "http://images.huxiu.com/article/cover/201509/14/074513891816.jpg" file:

var options = {  hostname: ‘images.huxiu.com‘,  port: 80,  method: ‘GET‘,  path: ‘/article/cover/201509/14/074513891816.jpg‘,  keepAlive: false};

The Http.request () method returns an HTTP. Clientrequest instance, after calling Http.request (), the req.end must be called one time after the tune, similar to the following:

var req = http.request(options, function(res){  console.log(res.statusCode);});...req.end();

Otherwise, the request will not be sent out Oh, your program will "stay" where, bewildered.

The use of Http.get () does not call Req.end (), because Http.get () automatically helps us.

We see that both http.request () and Http.get () have a callback method, and the parameter res of this callback method is HTTP. An instance of Incomingmessage, a readable Stream, through which we can get the status and data returned by the server.

Instead of providing callbacks to Http.request () and Http.get (), we can actually handle the service-side feedback by listening to the Clientrequest response event. As you expected, the callbacks required for the response event are exactly the same as the Http.request () and Http.get (). The code looks like this:

var req = http.request(options);...req.end();req.on(‘response‘, function(res){  ...});
A small example of downloading a picture

The example is simple, download a picture and write the file, and then exit when you are done. The code is as follows:

var http = require (' http '); var fs = require (' FS ');//req is an instance of HTTP. Clientrequestvar req = http.get (' http://images.huxiu.com/article/cover/201509/14/074513891816.jpg ');/*var options = {hostname: ' images.huxiu.com ', port:80, Method: ' GET ', Path: '/article/cover/201509/14/074513891816.jpg ', keepAlive : False};var req = http.request (options, function (res) {console.log (res.statuscode);}); /req.end () must was called while Http.request () was use to issue a requestreq.end (); */req.on (' Error ', function (e) {Console. Log (e);});  var Savedstream = Null;var SAVEDFD = 0;function endsaved () {if (Savedstream! = null) {savedstream.end (); }}//res is an instance of Http.incomingMessagereq.on (' response ', function (res) {Console.log (' StatusCode-', RES.STATUSC  ODE);  Console.log (' ContentLength-', res.headers[' content-length ']);    if (Res.statuscode = =) {SAVEDFD = Fs.opensync (' test.jpg ', ' W '); if (SAVEDFD >-1) {Savedstream = Fs.createwritestream (' test.jpg ', {FD:SAVEDFD});      Console.log (' write stream created. ');        Savedstream.on (' Finish ', function () {console.log (' data saved finished. ');      Process.exit (0);    });    }}else{Console.log (' Error occured. ');  Process.exit (1);    } res.on (' Data ', function (chunk) {//console.log (' Got data-', chunk);           if (savedstream! = null) {if (Savedstream.write (chunk)) {console.log (' data write directly. ');  }    }  });      Res.on (' Close ', function () {Console.log (' res closed, end save now. ');  Endsaved ();  });    Res.on (' End ', function () {Console.log (' res end, end save now. ');  Endsaved ();  });    Res.on (' Error ', function (e) {console.log (' res err, end save now. ');  Endsaved (); });});

I use the Http.get () method to download pictures. Also tested Http.request (), The annotated code is, open it, Block Http.get () that line of code is OK.

When the file download is complete, res (HTTP. Incomingmessage) launches an event named "End" and I listen to it to close the saved file.

Note I monitor req (http. Clientrequest) Response event to handle feedback from the server. I used the Fs.opensync () when I opened the file, and I took a synchronous approach, which made the programming easier. Fs.opensync () returns a file descriptor (FD), which I pass to Fs.createwritestream to create a Fs.writestream instance, and then use it to write the file.

Other articles:

    • Getting Started with node. JS Development-SOCKET (socket) programming
    • node. JS Development Primer--notepad++ for node. js
    • Get started with node. JS-Use dialog box Ngdialog
    • Introduction to node. JS Development--Introducing Uibootstrap
    • Get started with node. JS-Transform Logindemo with MongoDB
    • node. JS Development Primer--mongodb and Mongoose
    • Get started with node. JS Development-Use cookies to stay signed in
    • Getting Started with node. JS-Using ANGULARJS built-in services
    • node. JS Development Primer--angular Simple Example
    • Introduction to node. JS Development-Using ANGULARJS
    • Getting Started with node. JS Development-Using the Jade template engine
    • node. JS Development Starter--express Routing and middleware
    • node. JS Development Primer--express Installation and use
    • node. JS Development Primer--http File Server
    • node. JS Development Primer--helloworld Re-analysis
    • Introduction to node. JS Development--Environment building and HelloWorld

Copyright NOTICE: This article is Foruok original article, without BO Master permission cannot reprint.

Getting Started with node. JS-Accessing the outside world using HTTP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.