Skip to content

How to write a JSON object to file in Node.js

Discover how to save a JSON object to file in Node.js, and retrieve it later

Sometimes the best way to store some data in a Node.js application is to save it to the filesystem.

If you have an object that can be serialized to JSON, you can use the JSON.stringify() method and the fs method fs.writeFileSync() which synchronously writes a piece of data to a file:

const fs = require('fs')

const storeData = (data, path) => {
  try {
    fs.writeFileSync(path, JSON.stringify(data))
  } catch (err) {
    console.error(err)
  }
}

To retrieve the data, you can use fs.readFileSync():

const loadData = (path) => {
  try {
    return fs.readFileSync(path, 'utf8')
  } catch (err) {
    console.error(err)
    return false
  }
}

We used a synchronous API, so we can easily return the data once we get it.

We can also decide to use the asynchronous versions, fs.writeFile and fs.readFile, although the code will change a little bit, and I recommend you take a read at how to write files using Node.js and how to read files using Node.js for this.


→ Get my Node.js Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list