Read JSON Files In NodeJS With require() and fs.readFileSync()
In this post we will give you information about Read JSON Files In NodeJS With require() and fs.readFileSync(). Hear we will give you detail about Read JSON Files In NodeJS With require() and fs.readFileSync()And how to use it also give you demo for it if it is necessary.
In Node.js you have two methods for reading JSON files require()
and fs.readFileSync()
.
For static JSON files, use the require()
method because it caches the file. but for dynamic JSON file the fs.readFileSync()
is preferred.
After reading the JSON file using fs.readFileSync()
method, you need to parse the JSON data using the JSON.parse()
method.
Using the require method, you can read your JSON file in one line of code as follows:
letdata=require('./file.json')
Using the fs.readFileSync()
method, you cann read the file in two lines of code:
constfs=require('fs')letdata=JSON.parse(fs.readFileSync('file.json','utf-8'))
Hope this code and post will helped you for implement Read JSON Files In NodeJS With require() and fs.readFileSync(). if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs