Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node.js / Express, how do I "download" a page and gets its HTML?

Inside the code, I want to download "http://www.google.com" and store it in a string. I know how to do that in urllib in python. But how do you do it in Node.JS + Express?

like image 855
TIMEX Avatar asked Apr 27 '11 08:04

TIMEX


People also ask

How do I download from Express js?

Step 1: create an “app. js” file and initialize your project with npm. Step 2: Now install two npm packages: “express” and “express-zip“. Step 3: Create an “index.


3 Answers

var util = require("util"),     http = require("http");  var options = {     host: "www.google.com",     port: 80,     path: "/" };  var content = "";     var req = http.request(options, function(res) {     res.setEncoding("utf8");     res.on("data", function (chunk) {         content += chunk;     });      res.on("end", function () {         util.log(content);     }); });  req.end(); 
like image 84
yojimbo87 Avatar answered Sep 19 '22 17:09

yojimbo87


Using node.js you can just use the http.request method

http://nodejs.org/docs/v0.4.7/api/all.html#http.request

This method is built into node you just need to require http.

If you just want to do a GET, then you can use http.get

http://nodejs.org/docs/v0.4.7/api/all.html#http.get

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/index.html'
};

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

(Example from node.js docs)

You could also use mikeal's request module

https://github.com/mikeal/request

like image 26
David Avatar answered Sep 22 '22 17:09

David


Simple short and efficient code :)

var request = require("request");

request(
    { uri: "http://www.sitepoint.com" },
    function(error, response, body) {
        console.log(body);
    }
);

doc link : https://github.com/request/request

like image 20
Natesh bhat Avatar answered Sep 18 '22 17:09

Natesh bhat