[英]How to get value from modified object in Node.js
如何获取对象的修改值? 在index2.js object.js之前调用index.js
var object = { size:'5' }; var setSize = function(size) { object.size = size; } exports.object = object; exports.setSize = setSize;
index.js
var obj = require('path/object'); obj.setSize('10'); console.log(obj.object.size); //--> 10
index2.js我希望结果为10。
var obj = require('path/object'); console.log(obj.object.size); //--> 5
如果将node index.js
与node index2.js
分开运行,则index2.js
无法“知道”在index.js
的最后一个过程中发生了什么。 您必须在单个流程运行中应用所有操作。 正如@Andrew Li在其评论中所述,您将必须在index2.js
require
index.js
。 简单地要求它,将执行它的代码,并且对obj.object
的更改将保存在Nodes模块缓存机制中。
var obj = require('path/object');
require('./index');
// code inside index.js gets executed, changing obj.size to '10'
// note that this will also log '10' in the console, since a console.log(obj.size)
// is part of your code in index.js
console.log(obj.object.size) //--> 10
如果需要在不同的进程中执行index.js
和index2.js
,但仍然能够访问obj
的一致值,则需要将该值存储在进程空间之外的某个位置,例如在数据库或文件系统中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.