[英]How do I access my object array as a datastore across multiple node modules in 'use strict' mode?
So I am using an object array as my datastore. 所以我正在使用对象数组作为数据存储。 Every module is in 'use strict' mode so globals do not work.
每个模块都处于“严格使用”模式,因此全局变量不起作用。 I tried creating aa single module to store my data and including it on several modules, however it fails to work.
我尝试创建一个模块来存储我的数据并将其包含在多个模块中,但是它无法正常工作。
list.js
'use strict';
module.exports.list = [];
I'll have other files access this, for example, the main code, and then a test file. 我将有其他文件访问此文件,例如,主代码,然后是测试文件。 I need to be able to access and manipulate the array from every file list is included.
我需要能够从包含的每个文件列表中访问和操作数组。 All i get is modules crashing.
我所得到的只是模块崩溃。
code.js
var list = require('./list.js').list;
list = [{id:1},{id:2},{id:3}];
Trying to run the specs, just crashes everything, removing the datastore makes tests fail. 尝试运行规格,只会使所有程序崩溃,删除数据存储区会使测试失败。
code_spec.js
--tests code_spec.js
测试
var list = require('./list.js').list;
fixtures = [{id:1},{id:2},{id:3}];
list = fixtures;
You aren't actually updating the singleton instance of list. 您实际上并没有更新list的单例实例。 You want to use a setter and a getter for this.
您要为此使用一个setter和一个getter。 You can use the concept of
closures
for this to access the local variable inside list.js. 您可以使用
closures
的概念来访问list.js中的局部变量。
//list.js
var list = [];
module.exports.get = function () {
return list;
}
module.exports.set = function (ll) {
if (Array.isArray(ll)) {
list = ll
}
}
and how to use it in your other file: 以及如何在其他文件中使用它:
//other.js
var listService = require('./list');
list = listService.get();
newList = listService.set([{id:1}, {id:2}, {id:3}]);
console.log(listService.get()); //[{id:1}, {id:2}, {id:3}]
Another possiblity which I would only use for certain things is to use the global
object: 我只会在某些事情上使用的另一种可能性是使用
global
对象:
global.list = [{id:1}, {id:2}, {id:3}];
this can be used throughout the app. 这可以在整个应用程序中使用。 But DON'T polute your global space.
但是不要污染您的全球空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.