Node.js在module.exports我var是underfined
我的variables“整体”是未定义的。
getStudents.js
var http = require('http'); module.exports = { 'sendResults': function(){ http.get(' http://gs-class.com/nodejs/students.php', function(res){ var whole = ''; res.on('data',function(chunk){ whole+=chunk; }); res.on('end', function(){ return whole; }); }); } }
studWrite.js
var getStudents = require('./getStudents'); var fs = require('fs'); var results = getStudents.sendResults(); console.log(results);
而当我运行程序studWrite.js我var'整个'是未定义的。 请帮助。
尝试这个:
studWrite.js
var getStudents = require('./getStudents'); var fs = require('fs'); getStudents.sendResults(function(result) { console.log(result); });
getStudents.js
var http = require('http'); module.exports = { 'sendResults': function(callback) { http.get(' http://gs-class.com/nodejs/students.php', function(res) { var whole = ''; res.on('data', function(chunk) { whole += chunk; }); res.on('end', function() { callback(whole) }); }); } }
您需要使用asynchronous方法(callback,承诺)来解决问题。