node.js全局变量
发布于 12 年前 作者 VDON 7737 次预览 最后一次回复是 12 年前 来自
想要读取文件中的内容后输出,后来想做成一个函数,可是参数好像传不出来。 用return表示undefined,下面这种写法也不行,怎么破?
var fs = require('fs');
function hellof() {
fs.readFile('hello.txt', 'utf-8', function (err, data) {
if (err) {
console.log('if');
console.error(err);
} else {
console.log(data);
global.name = data;
}
});
}
hellof();
console.log(global.name);4 回复
function hellof(cb) { fs.readFile(‘hello.txt’, ‘utf-8’, function (err, data) { if (err) { console.log(‘if’); console.error(err); } else { cb(data); global.name = data;
} }); }
hellof(function(data){ console.log(data); });
你的程序里,console.log(global.name); 执行的时候,global.name 还没有被赋值。
回调函数什么时候执行不一定的,所以肯定没办法啊