JavaScript - reading JSON file with require gives different result than fs.readFileSync

Viewed 154

I'm getting an issue that makes me think there's something I'm missing about how require works in JavaScript. Basically, if I use require to read a JSON file, I get a different result than using fs.readFileSync.

I start with a JSON file with the following contents:

{"text":"old text"}

I first read the file with require and fs.readFileSync and get the same results for each. I then update the file with fs.writeFileSync and read the file again with require and fs.readFileSync, but I get different results after updating.

It's important to note that I'm requiring the file from inside a function. I would expect this to import the file separately with each function call, but that's apparently not what's happening. Just wondering if someone can explain exactly what's happening.

const fs = require('fs');
const textPath = './test.json';

const oldTextJSON = getText();  // prints as "old text"
const oldTextRead = JSON.parse(fs.readFileSync(textPath)).text;  // prints as "old text"

fs.writeFileSync(textPath, JSON.stringify({
  text: "new text"
}));

const newTextJson = getText();  // prints as "old text"
const newTextRead = JSON.parse(fs.readFileSync(textPath)).text;  // prints as "new text"

function getText() {
  return require(textPath).text;
}
1 Answers

Hope this one line explain the characteristics of require.

const path = require("path");


const filepath = path.resolve(textPath);
delete require.cache[filepath];

Basically require reads from the cache no matter how many times you call.

Related