节点 js 是否需要,在 运行 时间更新值?
Does require in node js, updates value at run time?
我有类似的东西
var some_data=require('../objects/some_data.json');
function(){
//something here to change data of some_data.json - fs.write
//vl this affect value of some_data at this point ?
}
是否需要保持对文件的主动引用或在需要时只读取一次?
如果它保持活动 ref ,我如何保留 some_data
的旧值
它保持活跃的参考。即通过require加载的对象是单例的。
来自 https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders :
Modules are cached after the first time they are loaded.
Multiple calls to require('foo') may not cause the module code to be executed multiple times.
假设您有一个名为 deleteme.json
的文件,其中包含以下内容:
{
"key": "value"
}
让我们尝试要求它,更改它,然后再次要求它:
var data = require('./deleteme.json')
data.key = "newvalue"
data = require('./deleteme.json')
console.log(data)
您会看到它记录 newvalue
- 由于对象未重新加载,原始对象保留在内存中。
既然您询问了删除文件的问题:您可以删除该文件,因为它在内存中。删除文件只会在您再次启动节点并首次加载模块时停止。
它加载文件,启动时的情况。它不会对 json 文件进行任何更改。
例如,运行这个
var b = require("./a.json");
for (var i = 0; i< 1000000; i++) {
console.log(b.a);
}
用这个jsona.json
{
"a": "b"
}
并在循环中更改值 - 或删除文件。它仍然有效。
我有类似的东西
var some_data=require('../objects/some_data.json');
function(){
//something here to change data of some_data.json - fs.write
//vl this affect value of some_data at this point ?
}
是否需要保持对文件的主动引用或在需要时只读取一次?
如果它保持活动 ref ,我如何保留 some_data
的旧值它保持活跃的参考。即通过require加载的对象是单例的。
来自 https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders :
Modules are cached after the first time they are loaded.
Multiple calls to require('foo') may not cause the module code to be executed multiple times.
假设您有一个名为 deleteme.json
的文件,其中包含以下内容:
{
"key": "value"
}
让我们尝试要求它,更改它,然后再次要求它:
var data = require('./deleteme.json')
data.key = "newvalue"
data = require('./deleteme.json')
console.log(data)
您会看到它记录 newvalue
- 由于对象未重新加载,原始对象保留在内存中。
既然您询问了删除文件的问题:您可以删除该文件,因为它在内存中。删除文件只会在您再次启动节点并首次加载模块时停止。
它加载文件,启动时的情况。它不会对 json 文件进行任何更改。
例如,运行这个
var b = require("./a.json");
for (var i = 0; i< 1000000; i++) {
console.log(b.a);
}
用这个jsona.json
{
"a": "b"
}
并在循环中更改值 - 或删除文件。它仍然有效。