Created
November 18, 2021 00:52
-
-
Save w3collective/908c1d3844dca1cc9d35d8d809e17474 to your computer and use it in GitHub Desktop.
Read and write JSON files using Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const books = [ | |
{ | |
title: "The Great Gatsby", | |
author: "F. Scott Fitzgerald", | |
}, | |
{ | |
title: "Frankenstein", | |
author: "Mary Shelley", | |
}, | |
{ | |
title: "The Call of the Wild", | |
author: "Jack London", | |
}, | |
]; | |
const data = JSON.stringify(books); | |
fs.writeFile("./data.json", data, "utf8", (error) => { | |
if (error) { | |
console.log(error); | |
} else { | |
console.log("writeFile complete"); | |
} | |
}); | |
fs.readFile("./data.json", "utf8", (error, json) => { | |
if (error) { | |
console.log(error); | |
return; | |
} | |
try { | |
const books = JSON.parse(json); | |
books.forEach((book) => { | |
console.log(`${book.title} by ${book.author}`); | |
}); | |
} catch (error) { | |
console.log(error); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source => https://w3collective.com/node-read-write-json/