2- Inside the file, create a dependency to node.js' file system
var fs = require('fs')
Please note: variable fs can have any other variable name3- Let's create a simple json file, call it data.json
Inside the file, let's add:
{"name":"Tim"}
4- Save the file and go back to demo.js5- Now that we have loaded the file system module, we are able to use the readFile() function to read the json file
6- In demo.js, add:
fs.readFile('./data.json', function(err,data){console.log(data)})
orfs.readFile('./data.json', (err,data)=>{console.log(data)})
The second one is used more often since it is more compact.
The readFile() function allows you to use an anonymous function as a second parameter. In this anonymous function, you allow for error display and specified json file's data will be saved in a data variable. We then output the data in the console.
In this case, the output will be something like:
<Buffer 7b 0d 0a 20 20 22 6e 61 6d 65 22 3a 20 22 54 69 6d 22 0d 0a 7d 0d 0a>
This is because we need to specify the utf-8 format. It will look like this:
fs.readFile('./data.json', 'utf-8', (err,data)=>{console.log(data)})
Now the output will be:
{"name":"Tim"}
To read the exact value, we will need to treat the name property as an object by using:
var data = require('./data.json')
To see the output, use:
console.log(data.name)
An alternate way (using the previous example) is to use JSON.parse() to create the object:
fs.readFile('./data.json', (err,data)=>{var data = JSON.parse(data) console.log(data.name)})
Output for both examples will be:
Tim
Final code (using both methods):
var fs = require('fs')
var data = require('./data.json')
console.log(data.name)
fs.readFile('./data.json', 'utf-8', (err,data) => {
var data = JSON.parse(data)
console.log(data.name)
})
No comments:
Post a Comment