我想使用node js返回文件的内容

I want to return the contents of file using node js

本文关键字:文件 返回 js node      更新时间:2023-09-26

我用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");
        }
    });

也,在一个不相关的注意,var关键字在helper定义中缺失,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();