如何将数据保存在本地JSON文件中作为节点中的变量?

时间:2018-08-10 15:16:05

标签: json node.js

enter image description here

上面的代码有效,但是我想从JSON文件中加载searchStrings数组。

enter image description here

我的目标是将json文件放在共享驱动器上,以便我的同事能够编辑名称。

3 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

{{1}}

答案 1 :(得分:0)

可以像节点模块一样通过require导入

JSON。 (请参见Ben Nadel's explanation。)

通常,您希望将其存储为全局变量,而不是在每个keyup事件中重新加载它。因此,如果JSON另存为watchlist.json,则可以添加

var watchlist = require('./watchlist');

位于代码顶部。然后可以将搜索命令编写为(不需要for循环):

kitten = kitten.toLowerCase();
if (watchlist.entities.indexOf(kitten) !== -1) {
  alert('potential watchlist');
}

答案 2 :(得分:0)

在最新版本的Node中,您只需使用导入即可!

常见问题解答

const jsonContent = require('path/to/json/file.json')

ES6:

import jsonContent from 'path/to/json/file.json'

您还可以通过以下示例动态导入JSon文件:

if (condition) {
 const jsonContent = require('path/to/json/file.json')
 // Use JSon content as you prefer!
}

那样,只有真正需要时才加载JSon文件,并且代码会获得更好的性能!

您喜欢老式的方法吗?

ES6:

import fs from 'fs' // or const fs = require('fs') in CommonJs

const JSonFile = fs.readFileSync('path/to/json/file.json', 'utf8')
const toObject = JSON.parse(JSonFile)

// read properties from `toObject` constant!

希望它会有所帮助:)