简体   繁体   English

我可以将json文件用作node.js中的模块吗

[英]Can I use json file as a module in node.js

I have a JSON module which contains empty containers like this: 我有一个JSON模块,其中包含这样的空容器:

{
    "files": {
        "rootNeeded":[],
        "folders":[],
        "files":[],
        "images":[],
        "text":[],
        "unknown":[]
    },
}

and I wonder if I can push data into this from another module simply by using array.push method. 我想知道是否可以仅使用array.push方法将数据从另一个模块推array.push Something like ... 就像是 ...

var myModule=require("./myJsonFile");
function(){
    some magic here...
    myModule.files.files.push(files);
}

and after this can I use this in a third node module like this... 然后可以在第三个节点模块中使用它...

//my third module
console.log(files.files)

in the end it will be like dynamic database each time when program called will be refreshed. 最终,每次被调用的程序都会刷新时,它就像动态数据库。

You can, however the changes you make will NOT be persisted. 您可以,但是所做的更改将不会保留。 Also, if you use cluster , every process will have a different version of your object. 同样,如果您使用cluster ,则每个进程将具有不同版本的对象。

myJsonFile.json myJsonFile.json

{
  "files": {
    "rootNeeded": [],
    "folders": [],
    "files": [],
    "images": [],
    "text": [],
    "unknown": []
  }
}

mod1.js mod1.js

var json = require('./myJsonFile');

function pushData() {
  json.files.files.push('test 1');
  json.files.files.push('test 2');
}

pushData();

mod2.js mod2.js

var json = require('./myJsonFile');
require('./mod1');

console.log(json);

// { files: 
//   { rootNeeded: [],
//     folders: [],
//     files: [ 'test 1', 'test 2' ],
//     images: [],
//     text: [],
//     unknown: [] } }

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

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