[英]I want to return the contents of file using node js
我用量角器编写了以下代码。
var fs = require('fs');
helper = function(){
this.blnReturn = function(){
var filePath = '../Protractor_PgObjModel/Results/DontDelete.txt';
fs.readFileSync(filePath, {encoding: 'utf-8'}, function (err, data){
if (!err) {
console.log(data);
return data;
} else {
return "False";
}
});
};
};
module.exports = new helper();
------------上面的js被调用的实际文件-------------------
describe("read contents of file",function(){
var helper = require("../GenericUtilities/helper.js");
it('To Test read data',function(){
console.log("helper test - " + helper.blnReturn());
});
});
-------输出-------------
helper test - undefined
非常感谢这方面的帮助,因为它阻碍了我的工作。
您在同步读取文件( readFileSync
)和异步( readFile
)之间感到困惑。
您正在尝试同步读取文件,但也使用回调参数,正确的方法是
return fs.readFileSync(filePath, {encoding: 'utf-8'});
要么
this.blnReturn = function(cb){
...
fs.readFileSync(filePath, {encoding: 'utf-8'}, function (err, data){
if (!err) {
console.log(data);
cb(data);
} else {
cb("False");
}
});
另外,不相关的注释是, helper
定义中缺少var
关键字,可以将helper.js简化为:
var fs = require('fs');
function helper(){}
helper.prototype.blnReturn = function(){
var filePath = '../request.js';
return fs.readFileSync(filePath, {encoding: 'utf-8'});
};
module.exports = new helper();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.