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-------------------
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
).
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:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.