Require vs. fs.readFile reads JSON files
This is the 16th day of my participation in the August More Text Challenge.
background
There was a problem with the time management tool
In the code, require is used to read the JSON file. After the server starts up, it finds that when the JSON file is changed, it still returns the original JSON content
In the spirit of breaking the casserole pot to ask low spirit, launched a data access to explore, the opportunity to learn a wave of new knowledge
why
Conclusion First, modules introduced by require are cached by Node, so let’s use a simple demo to test this out
The sample
test-module.js
console.log('1');
module.exports = {
name:'0'
}
Copy the code
const m1 = require('./test-module')
m1.name = '2'
const m2 = require('./test-module')
console.log(m2.name);
Copy the code
The following output is displayed
1
2
Copy the code
From this we can conclude that Node caches imported modules. How does name view cached modules
Check the cache
Require. Cache to obtain the cached module:
- Return an object
const m1 = require('./test-module')
console.log(require.cache);
Copy the code
The output is as follows (a screenshot is posted here)
Delete the cache
Since require.cache returns a generic object, name can be removed by the delete keyword
const m1 = require('./test-module')
m1.name = '2'
console.log(m1.name);
delete require.cache[`${__dirname}/test-module.js`]
const m2 = require('./test-module')
console.log(m2.name);
Copy the code
The output is as follows
1
2
1
0
Copy the code
With the reasons out of the way, let’s get to the point
Comparative analysis of reading JSON files is performed
Read JSON comparison
- Require can be omitted
.json
The suffix - Fs.readfile reads cannot omit the suffix
test.json
{
"name":"xm"
}
Copy the code
Test the demo
const d1 = require('./test.json')
console.log(d1); // { name: 'xm' }
const d2 = require('./test')
console.log(d2); // { name: 'xm' }
Copy the code
Other differences
coding
- The require only by
utf-8
Format to read - fs.readFile
Sync
canSet encoding format
Asynchronous synchronous
- Require is synchronous reading
- through
fs
It can be read synchronously or asynchronously
summary
require
Support the cacherequire
Only utF-8 can read the contentrequire
Is synchronousrequire
Reading the JSON file can be omitted.json
The suffix
The last
The content of this article is relatively concise, for part-time students to learn Node may miss this part of the knowledge
We will continue to update the practice content of the time management tool