我在check_version.js文件中有如下代码: var fs = require(‘fs’); exports.version = function(path){ fs.readFile(path, ‘utf-8’, function(err, data){ if(err) throw err; var version = data.split(’=’); var version_num = version1.substr(1, 10) ; return version_num; }) ; } ;
我想return version_num的值,然后我在01.js文件中调用export的模块,代码如下: 01.js var check_version = require(’./check_version.js’); var assert = require(‘assert’); //var expect = ‘0801004067’; var path = ‘D:/nodejs/version.ini’; var actual = check_version.version(path); console.log(actual); 我执行01.js返回的结果是
console.log(actual);打印出来的是undefined,不知道为什么获取不到return的值
node里面要获得方法返回值一般不会直接用等号,像这样:var result=someFunction(); 而是传一个callback进去:
// the definition of the function
function someFunction(callback){
//do some work
callback('true')//invoke the callback to give it the result;
}
//invoke the function
someFunction(function callback(result){
//now you get the result;
});
将代码改成这样:
var fs = require('fs');
exports.version = function (path, callback) {
fs.readFile(path, 'utf-8', function (err, data) {
if (err) return callback(err);
var version = data.split('=');
var version_num = version1.substr(1, 10) ;
callback(null, version_num);
}) ;
} ;
这样获取版本:
check_version.version(path, function (err, actual) {
console.log(actual);
});
老雷霸气V5!
谢啦,学习了
或者改成这样:
var fs = require('fs');
exports.version = function (path) {
var data = fs.readFileSync(path, 'utf-8');
var version = data.split('=');
var version_num = version1.substr(1, 10) ;
return version_num;
} ;
这样获取版本:
var actual = check_version.version(path);
console.log(actual);
注意fs.readFile()和fs.readFileSync()的区别
后面那个是同步的方法吧
@snoopy 霸气侧露
我想顺便问下,断言的功能不,我想加个断言判断下获取的那个version_num值是不是跟预期的一致,我加了个断言,但是貌似它没被执行,代码如下 var check_version = require(’./check_version.js’); var assert = require(‘assert’); var expect = ‘0801004067’; var path = ‘D:/nodejs/version.ini’; check_version.version(path, function(actual){ console.log(actual);
assert.equal(actual, expect,'they are expected');
assert.ok(true, 'testrtest');
});