我有以下两个文件,无法将模块请求的结果输入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
}
答案 0 :(得分:1)
由于模块中的导出函数是异步的,因此您需要从应用程序通过回调处理其结果 在您的应用中:
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
}