0

I want to assign the content of the site acquired by specifying by URL to a variable.

Source

request-sample.js

var request = require('request');

var html = '';

request('https://www.google.com', function(error, response, body) {
  html = body;
});

// Below, proceed with processing using saved contents
console.log(html);

Result

$ node request-sample.js
$
(Nothing is output...)

How can I solve it?

ina6ra
  • 11
  • 3
  • do `console.log(html)` inside the callback `request('https://www.google.com', function(error, response, body) { html = body; console.log(html); });` – parwatcodes Apr 03 '17 at 12:09
  • @p0k8_ Thank you for your quick answer! I would like to use saved content outside of request. Can not you do that? – ina6ra Apr 03 '17 at 12:15
  • have a look at promises and async.js – parwatcodes Apr 03 '17 at 12:16
  • @p0k8_ Thank you for information! After examining, I found a [request-promise](https://github.com/request/request-promise). This seems to be solved. – ina6ra Apr 03 '17 at 12:27
  • @ponury-kostek Thank you for information! I will refer to the linked article. – ina6ra Apr 03 '17 at 12:28
  • @ina6ra yes using request-promise, you can perform your stuffs, after the successful `.then` handler – parwatcodes Apr 03 '17 at 12:58
  • @p0k8_ It solved it by using [sync-request](https://www.npmjs.com/package/sync-request). It seems to be deprecated, but I just want to use it for testing, so it is good. – ina6ra Apr 03 '17 at 14:04

0 Answers0