November
11th,
2016
First, we need to have a JSON file with empty array or existing array with objects. Suppose this users.json
:
{
"users": []
}
For append new content to users.json
file we need to read the file and convert it contents to an JavaScript object using JSON.parse()
method:
var fs = require('fs')
fs.readFile('./users.json', 'utf-8', function(err, data) {
if (err) throw err
var arrayOfObjects = JSON.parse(data)
})
Now arrayOfObjects
variable contains a object from users.json
file:
console.log(arrayOfObjects)
// Output: { users: [] }
Now we can write the data into an users
array using the push()
method is as follows:
var fs = require('fs')
fs.readFile('./users.json', 'utf-8', function(err, data) {
if (err) throw err
var arrayOfObjects = JSON.parse(data)
arrayOfObjects.users.push({
name: "Mikhail",
age: 24
})
console.log(arrayOfObjects)
})
Now we have an array with an object:
console.log(arrayOfObjects)
// Output: { users: [ { name: 'Mikhail', age: 24 } ] }
You can appended any objects to users
array.
After we have data in variable we need to write this into file:
fs.writeFile('./users.json', JSON.stringify(arrayOfObjects), 'utf-8', function(err) {
if (err) throw err
console.log('Done!')
})
You may have noticed that here uses JSON.stringify(arrayOfObjects)
. JSON.stringify()
method convert the contents of arrayOfObjects
into JSON.
Now users.json
looks like this:
{
"users": [
{
"name": "Mikhail",
"age": 24
}
]
}
Full Code:
index.js
var fs = require('fs')
fs.readFile('./users.json', 'utf-8', function(err, data) {
if (err) throw err
var arrayOfObjects = JSON.parse(data)
arrayOfObjects.users.push({
name: "Mikhail",
age: 24
})
console.log(arrayOfObjects)
fs.writeFile('./users.json', JSON.stringify(arrayOfObjects), 'utf-8', function(err) {
if (err) throw err
console.log('Done!')
})
})
users.json
{
"users": []
}