简体   繁体   中英

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

I'm working on a nodejs program, in the program I need to be able to check a variable inside a JSON file that will be switched via a different program. I started working on an if statement to figure it out, I soon found out that nodejs doesn't like it when i go around switching variables after the code has been ran. I ran a code that looked a little like this:

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

I would trigger the event, change the json manually then trigger it again the output would look like this

true
true

meaning that it would NOT read the json file after i change it

I tried to force it to 're require' the JSON file in the code above but that hasn't worked, Ive tried running it in a fresh nodejs script to see if it was because of a statement it could possibly be inside the code looked like this

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

i would change the variable and the output would keep outputting true or false

that didnt work.

Geshode wrote a comment that said: 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?

that worked i put it as an answer so other people can see it, if you need heres some code samples

to read a json file:

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

if edited correctly should output a variable inside of your json file

to read WITHOUT making it a json object

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

note: the only differences between these samples is the second one dosnt make it into a json file it will do the same thing if you replace data in console.log(data) to student.varable and add JSON.parse(data) above it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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