javascript - 如何在 Node.js 中的 fs.readFile 中使用 'this' 引用

标签 javascript node.js this readfile

我想使用 JavaScript 类的 this 关键字使用 fs.readFile 方法从文件中填充对象列表

var MyReaderClass = (function() {
    //Const    

    function MyReaderClass() {
        this.readObjects = [];

        /**    
         * Default constructor for the MyReaderClass class
         */
        var _constructor = function() {

        }

        _constructor.call(this);
    }

    //Public    
    MyReaderClass.prototype.ReadFiles = function(p_path) {
        var files = fs.readdirSync(p_path);

        for (var i in files) {
            var fileName = files[i];
            fs.readFile(path.join(p_path, fileName), 'utf8', function(err, data) {
                if (err) {
                    return console.log(err);
                } 
                else {
                    var formattedData = /*... Logic to format my data into an object*/;
                    this.readObject.push(formattedData); //The "this" is not the reference to my class.
                }
            });
        }
    }
    return MyReaderClass;
})();

即使我正在创建 this 变量的本地实例(_self、that、实例等),在 readFile 方法之外,我的本地实例也会获胜不要被填满。

知道如何实现这个目标吗?

最佳答案

readFile 是异步方法,您会丢失执行上下文。您需要将您的类绑定(bind)到 readFile 回调作为上下文。使用Function.prototype.bind:

MyReaderClass.prototype.ReadFiles = function(p_path) {
    var files = fs.readdirSync(p_path);
    for (var i in files) {
        var fileName = files[i];
        fs.readFile(path.join(p_path, fileName), 'utf8', function(err, data) {
            /*readFile callback*/
        }.bind(this));//also here was a syntax error
    }
}

关于javascript - 如何在 Node.js 中的 fs.readFile 中使用 'this' 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21557571/

相关文章:

javascript - 为简单的 javascript 打字机添加字体覆盖

node.js - Strapi CMS,Heroku 错误 : no pg_hba. 主机的 conf 条目

javascript - 如何将 JSON 响应的特定元素插入数组?

node.js - 如何使用 Node Puppeteer 设置 select 的值

javascript - VueJS : why is "this" undefined?

c++ - 在C++线程对象中重新绑定(bind)*this, move 构造函数, move 赋值

javascript - 'this' 在下一个范围内未定义

javascript - 加载更多按钮不起作用

javascript - 如何在 React 中使用 prop 双向绑定(bind) select 元素

javascript - 在应用半透明覆盖层后以编程方式计算实现特定颜色所需的基色