如何从nodejs模块中的请求中获取变量

How to get variable from request in nodejs module

我有以下两个文件,无法从我的模块请求中获取结果到 app.js 中的 var。

我考虑过 module.exports 导出为回调,但我找不到合适的组合。

// app.js

#!/usr/bin/env node

// i am a nodejs app
var Myobject = require('./code.js');

var value1 = "http://google.com";

var results = Myobject(value1); // results should stare the results_of_request var value 

console.dir(results); // results should stare the results_of_request var value 

现在模块来了 // code.js

// i am a nodejs module
module.exports = function(get_this) {
  var request = require('request');
    var options = {
          url: get_this,
    };



  request(options, function(error, response, body) {
            if (!error) {
               // we got no error and request is finished lets set a var
               var result_of_function = '{"json":"string"}'
            }
    }
// the main problem is i have no way to get the result_of_function value inside app.js
}

由于您从模块中导出的函数是异步的,因此您的应用需要通过回调来处理其结果 在您的应用中:

Myobject(value1, function(err, results){
  //results== '{"json":"string"}'
});

在您的模块中:

module.exports = function(get_this, cbk) {
  var request = require('request');
    var options = {
          url: get_this,
    };

  request(options, function(error, response, body) {
            if (error) {
               return cbk(error);
             }
             // we got no error and request is finished lets set a var
             var result_of_function = '{"json":"string"}'
             return cbk(null, result_of_function)
    }
// the main problem is i have no way to get the result_of_function value inside app.js
}