Skip to content

Instantly share code, notes, and snippets.

@w3collective
Created November 18, 2021 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w3collective/908c1d3844dca1cc9d35d8d809e17474 to your computer and use it in GitHub Desktop.
Save w3collective/908c1d3844dca1cc9d35d8d809e17474 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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