我想要使用节点js返回文件的内容
我已经在量angular器中编写了下面的代码。
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
)和asynchronous( readFile
)之间的文件混淆。
你正在尝试同步读取文件,但也使用callback参数,正确的方法是要么
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
定义中缺lessvar
关键字,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();