[英]I want to return the contents of file using node js
I have written the following code in protractor. 我用量角器编写了以下代码。
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();
------------actual file where the above js is being called------------------- ------------上面的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());
});
});
-------Output------------- -------输出-------------
helper test - undefined
Any help in this regard is much appreciated as it is blocking my work. 非常感谢这方面的帮助,因为它阻碍了我的工作。
you are confusing between reading file synchronously( readFileSync
) and async( readFile
). 您在同步读取文件( readFileSync
)和异步( readFile
)之间感到困惑。
you are trying to read the file synchronously, but also using a callback parameter, the right way would be either 您正在尝试同步读取文件,但也使用回调参数,正确的方法是
return fs.readFileSync(filePath, {encoding: 'utf-8'});
or 要么
this.blnReturn = function(cb){
...
fs.readFileSync(filePath, {encoding: 'utf-8'}, function (err, data){
if (!err) {
console.log(data);
cb(data);
} else {
cb("False");
}
});
also, on an unrelated note, var
keyword is missing in helper
definition, the helper.js can be reduced to: 另外,不相关的注释是, 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.