模块代码:
const fs = require('fs');
class database {
constructor(database, object) {
typeof database === "object" && (object = database);
this.file = (typeof database === "string" ? database : 'db') + '.json';
object && fs.writeFileSync(this.file, JSON.stringify(object));
this.db = fs.existsSync(this.file) ? JSON.parse(fs.readFileSync(this.file, 'utf-8')) : {};
return new Proxy(this.db, this)
}
set(target, key, value) {
this.db[key] = value;
fs.writeFileSync(this.file, JSON.stringify(this.db));
}
}
module.exports = database;
示例脚本:
var db = require('./index.js')
var test = new db();
test.a = []; // Proxy is called here
test.a.push('a'); // It's not called here, despite test.a being set.
我希望set
处理程序在对象更新时触发,但是当推送到对象内部的数组时,它不会发生。为什么不开火?
我正在使用节点 v8.1.4。据说所有代理问题都在 v6 之后得到修复。