我在 Protractor 中编写了以下代码。
helper.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();
关于javascript - 我想使用node js返回文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31527328/