如何在 Node.js 的 fs.readFile 中使用“this"引用 [英] How to use the 'this' reference in fs.readFile in Node.js
问题描述
我想使用我的 JavaScript 类的 this
关键字使用 fs.readFile 方法从文件中填充对象列表
I would like to populate a list of object from a file using the fs.readFile method using the this
keyword of my JavaScript class
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;
})();
即使我正在创建此变量的本地实例(_self、that、instance 等
),在 readFile
方法之外,我的本地实例也获胜不会被填满.
Even if I'm creating a local instance (_self, that, instance, etc.
) of my this variable, outside the readFile
method, my local instance won't be filled up.
知道我如何做到这一点吗?
Any idea how I could accomplish this ?
推荐答案
readFile
是异步方法,您会丢失执行上下文
.您需要将您的类绑定到 readFile 回调作为上下文.使用 Function.prototype.bind
:
readFile
is async method and you lose your execute context
. You need bind your class to readFile callback as a context. Use 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
}
}
这篇关于如何在 Node.js 的 fs.readFile 中使用“this"引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!