Skip to content

Instantly share code, notes, and snippets.

@coffeepostal
Last active April 18, 2019 01:13
Show Gist options
  • Save coffeepostal/e3110f75bdce73ce4245bafff5a99ed2 to your computer and use it in GitHub Desktop.
Save coffeepostal/e3110f75bdce73ce4245bafff5a99ed2 to your computer and use it in GitHub Desktop.
NODE: Write to JSON File Using FileSystem
///////////////
// 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": []
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment