Skip to content

Instantly share code, notes, and snippets.

@eojthebrave
Created December 14, 2018 17:15
Show Gist options
  • Save eojthebrave/3854faeed80a62c084e686e29654e330 to your computer and use it in GitHub Desktop.
Save eojthebrave/3854faeed80a62c084e686e29654e330 to your computer and use it in GitHub Desktop.
// customer.json
{
"name": "Mega Corp.",
"order_count": 83,
"address": "Infinity Loop Drive",
}
const fs = require('fs')
fs.readFile('./customer.json', 'utf8', (err, jsonString) => {
if (err) {
console.log("File read failed:", err)
return
}
console.log('File data:', jsonString)
})
const fs = require('fs')
fs.readFile('./customer.json', 'utf8', (err, jsonString) => {
if (err) {
console.log("Error reading file from disk:", err)
return
}
try {
const customer = JSON.parse(jsonString)
console.log("Customer address is:", customer.address)
// => "Customer address is: Infinity Loop Drive"
} catch(err) {
console.log('Error parsing JSON string:', err)
}
})
try {
const jsonString = fs.readFileSync('./customer.json')
const customer = JSON.parse(jsonString)
} catch(err) {
console.log(err)
return
}
console.log(customer.address) // => "Infinity Loop Drive"
const fs = require('fs')
function jsonReader(filePath, cb) {
fs.readFile(filePath, (err, fileData) => {
if (err) {
return cb && cb(err)
}
try {
const object = JSON.parse(fileData)
return cb && cb(null, object)
} catch(err) {
return cb && cb(err)
}
})
}
jsonReader('./customer.json', (err, customer) => {
if (err) {
console.log(err)
return
}
console.log(customer.address) // => "Infinity Loop Drive"
})
const customer = {
name: "Newbie Corp.",
order_count: 0,
address: "Po Box City",
}
const jsonString = JSON.stringify(customer)
console.log(jsonString)
// => "{"name":"Newbie Co.","address":"Po Box City","order_count":0}"
const fs = require('fs')
const customer = {
name: "Newbie Co.",
order_count: 0,
address: "Po Box City",
}
const jsonString = JSON.stringify(customer)
fs.writeFile('./newCustomer.json', jsonString, err => {
if (err) {
console.log('Error writing file', err)
} else {
console.log('Successfully wrote file')
}
})
const jsonString = JSON.stringify(customer)
fs.writeFileSync('./newCustomer.json', jsonString)
jsonReader('./customer.json', (err, customer) => {
if (err) {
console.log('Error reading file:',err)
return
}
// increase customer order count by 1
customer.order_count += 1
fs.writeFile('./customer.json', JSON.stringify(customer), (err) => {
if (err) console.log('Error writing file:', err)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment