简体   繁体   English

如何从Node.js中的修改后的对象中获取价值

[英]How to get value from modified object in Node.js

how to get modified value of object? 如何获取对象的修改值? index.js is called before index2.js object.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 index.js

 var obj = require('path/object'); obj.setSize('10'); console.log(obj.object.size); //--> 10 

index2.js I want the result to be 10. index2.js我希望结果为10。

 var obj = require('path/object'); console.log(obj.object.size); //--> 5 

If you run node index.js separately from node index2.js , there is no way for index2.js to "know" what happened in the last process of index.js . 如果将node index.jsnode index2.js分开运行,则index2.js无法“知道”在index.js的最后一个过程中发生了什么。 You have to apply all your actions in a single process run. 您必须在单个流程运行中应用所有操作。 As @Andrew Li stated in his comment, you would have to require index.js in your index2.js . 正如@Andrew Li在其评论中所述,您将必须在index2.js require index.js Simply requiring it, will have it's code executed and the changes to obj.object will be saved in Nodes module caching mechanism. 简单地要求它,将执行它的代码,并且对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

If you need to have index.js and index2.js executed in different processes but still be able to access a coherent value of obj , you need to store that value somewhere outside of the process space, like in a database or in the filesystem. 如果需要在不同的进程中执行index.jsindex2.js ,但仍然能够访问obj的一致值,则需要将该值存储在进程空间之外的某个位置,例如在数据库或文件系统中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM