返回函数Node.js的值

时间:2016-12-10 09:05:34

标签: javascript node.js express return cheerio

我有一个从网页读取数据并将其发布到控制台中的函数,但是我想返回我读过的数据,并用它做一些其他的思考。而不是console.log(温度)我想返回温度值并执行console.log(下载(url))但它发布'undefined'。

//require https module
var https=require("https");
//require cheerio to use jquery-like and return a DOM tree
var cheerio=require('cheerio');
var global="";
//a function with url and callback par which connects to URL API and read the data
module.exports.download=function(url){
  //read the data\
  https.get(url,function(res){
    var data="";
    //add it to the data string
    res.on('data',function(chunk){
      data+=chunk;
    });
    //parse it with a callback function
    res.on('end',function(){
      var $=cheerio.load(data);
      var temperature=$("span.temp.swip").text();
     console.log(temperature);
    });
  }).on('error',function(err){
    console.log(err.message)
  });
}

//chose the url to connect
var Ploiesti='44.9417,26.0237';
var Brasov='45.597,25.5525';
var url='https://darksky.net/forecast/' + Ploiesti + '/si24/en';

//download(url);

1 个答案:

答案 0 :(得分:0)

所以你需要一个回调来为它分配变量并从任何地方获取,看看cb

var download = function(url, cb){
  //read the data\
  https.get(url,function(res){
    var data="";
    //add it to the data string
    res.on('data',function(chunk){
      data+=chunk;
    });
    //parse it with a callback function
    res.on('end',function(){
      var $=cheerio.load(data);
      var temperature=$("span.temp.swip").text();
      cb(temperature);
    });
  }).on('error',function(err){
    console.log(err.message)
  });
}

module.exports.download = download;

然后,如果您需要从网络上调用该功能,您需要一条路线,请使用Express并将之前的文件保存为download.js

var express = require('express'),
    app = express(),
    download = require('download.js');

app.get('/temperature', function (req, res) {
  // Get the temp
  var Ploiesti='44.9417,26.0237',
      Brasov='45.597,25.5525',
      url='https://darksky.net/forecast/' + Ploiesti + '/si24/en';

  download.download(url, function (temp) {
     // Send the response to the web
     res.json({ temperature: temp);
  });
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
});