Get started with Node. js development-access the external world with http and access with node. js

Source: Internet
Author: User

Get started with Node. js development-access the external world with http and access with node. js

Node. jsHttp ModuleYou can not only build servers, but also access other servers as client class libraries. The key lies in two methods:

  • Http. request (options [, callback])
  • Http. get (path [, callback])

Besides httpFileSystem ModuleAndStreamStream. Readable and stream. Writable.

Let's take a look at the relevant APIs.

API description

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

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 (), you must call req. end somewhere after the call, 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, and your program will "Stay" and be at a loss.

Http. get () does not require calling req. end () because http. get () automatically helps us.

We can see that http. request () and http. get () has a callback method. The res parameter of this callback method is http. an instance of IncomingMessage, a Readable Stream, which can be used to obtain the status and data returned by the server.

In fact, we can not provide callbacks to http. request () and http. get (), but handle server feedback by listening to the response event of ClientRequest. As expected, the callback and http. request () and http. get () of the response event are exactly the same. The code is similar to this:

var req = http.request(options);...req.end();req.on('response', function(res){  ...});
Small Example of downloading images

The example is relatively simple. Download an image and write it into the file. Then exit. 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 be called while http.request() is 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.statusCode);  console.log('contentLength - ', res.headers['content-length']);  if(res.statusCode == 200){    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 http. get () to download images. Http. request () is also tested. The annotated code is to open it and block the line of http. get () code.

When the file download is complete, res (http. IncomingMessage) will launch an event named "end" and I will listen to it to close the saved file.

Note that I listen to the response event of req (http. ClientRequest) to handle the feedback from the server. When opening the file, I used fs. openSync () and used the synchronization method, which made programming easier. Fs. openSync () returns a file descriptor (fd). I pass it to fs. createWriteStream to create a fs. WriteStream instance and then use it to write files.

Other articles:

  • Node. js development-socket programming
  • Getting started with Node. js development-notepad ++ for Node. js
  • Getting started with Node. js Development -- use the ngDialog dialog box
  • Getting started with Node. js Development -- introducing UIBootstrap
  • Getting started with Node. js development-using MongoDB to transform LoginDemo
  • Getting started with Node. js development-MongoDB and Mongoose
  • Getting started with Node. js development-Keep logging on with cookies
  • Get started with Node. js development-use AngularJS built-in services
  • Get started with Node. js development-Angular simple example
  • Get started with Node. js development-use AngularJS
  • Getting started with Node. js Development -- using the jade template engine
  • Introduction to Node. js development-routing and middleware in Express
  • Getting started with Node. js development-install and use Express
  • Node. js development-HTTP File Server
  • Getting started with Node. js Development -- HelloWorld Analysis
  • Node. js development entry-Environment setup and HelloWorld

Copyright Disclaimer: This article is an original foruok article and cannot be reproduced without the consent of the blogger.

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.