繁体   English   中英

对 json 文件进行更改后,如何让我的 nodejs 文件重新识别?

[英]how can i get my nodejs file to recongnice when a change has been made to a json file?

我正在开发一个 nodejs 程序,在程序中我需要能够检查 JSON 文件中的变量,该变量将通过不同的程序进行切换。 我开始研究 if 语句来解决这个问题,我很快发现 nodejs 不喜欢它,当我在代码运行后四处切换变量时。 我运行了一个看起来有点像这样的代码:

"wait for event"{
"code once event happens"
var jsonfile = require('./jsonfile.json')
console.log(jsonfile.variable)}

我会触发事件,手动更改 json 然后再次触发它,输出将如下所示

true
true

这意味着在我更改它后它不会读取 json 文件

我试图强制它在上面的代码中“需要”JSON文件,但没有奏效,我尝试在一个新的nodejs脚本中运行它,看看它是否是因为它可能在代码中像这样

while (true){
var file = require('file.json')
console.log(file.variable)}

我会改变变量,输出会继续输出truefalse

那没有用。

Geshode 写了一条评论说: Instead of using require, have you tried reading the json file with the native file system, like fs.readFile? Or a library like fs-extra? Instead of using require, have you tried reading the json file with the native file system, like fs.readFile? Or a library like fs-extra?

那行得通,我把它作为答案,这样其他人就可以看到它,如果你需要一些代码示例

读取 json 文件:

fs.readFile('pathtojson', 'utf8', function(err, data){
    let student = JSON.parse(data);
    // Display the file content
    console.log(student.avariableinfile);
  })

如果正确编辑应该在你的 json 文件中输出一个变量

在不使其成为 json 对象的情况下阅读

fs.readFile('pathtofile', 'utf8', function(err, data){
    // Display the file content
    console.log(data);
  });

注意:这些示例之间的唯一区别是第二个示例不会将其放入 json 文件中,如果您将console.log(data) data的数据替换为student.varable并在其上方添加JSON.parse(data) ,它将执行相同的操作

暂无
暂无

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

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