gpt4 book ai didi

javascript - ECMAScript/Node : is it possible to save an object instance or context to the filesystem?

转载 作者:行者123 更新时间:2023-11-30 15:07:26 24 4
gpt4 key购买 nike

是否可以将对象(类的实例)保存到文件系统,包括其内部值?

请不要标记为偏离主题。我知道即使这在某种程度上是可以实现的,但这也不是常见的做法。如果它是 hacky 也没关系。我只是好奇它是否可以实现,因为现在是星期天 8 点,我度过了漫长的一天。

function Node() {
let x = Math.random()
this.data = function() {
return x
}
}

let node1 = new Node()
// save it to the disk somehow as node1
saveNode('node1', node1)
// load it back from the disk into memory somehow, perhaps using eval??
let savedNode = loadNode('node1')

console.log(
savedNode.data(),
node1.data()
) /* these should be the same */

您可以通过使用“修饰符”函数作为 JSON.stringify 中的第二个参数来字符串化一个对象,包括它的函数,但这不会在这里起作用。

最佳答案

仅当对象(或类)合作时。不,通常不可能访问隐藏在闭包作用域后面的值。

但是你可以做类似的事情

class Node {
constructor(x = Math.random()) {
this.data = () => x;
}
toJSON() {
return {x: this.data()};
}
static fromJSON(obj) {
return new this(obj.x);
}
}

const fs = require("fs");
function save(name, obj) {
fs.writeFileSync(`./${name}.json`, JSON.stringify(obj), "utf-8");
}
function load(constr, name) {
return constr.fromJSON(JSON.parse(fs.readFileSync(`./${name}.json`, "utf-8");
}

let node1 = new Node();
save('node1', node1);
let savedNode = load(Node, 'node1');
console.log(savedNode.data(), node1.data())

关于javascript - ECMAScript/Node : is it possible to save an object instance or context to the filesystem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45535383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com