Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Read and write JSON files using Node.js
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);
}
});
@w3collective

This comment has been minimized.

Copy link
Owner Author

@w3collective w3collective commented Nov 18, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment