Writing Files with Node.js

Using good ol' fs module


Published on: March 2, 2020

Writing Files

  1. Import fs module (native to Node, no need to install from NPM)
const fs = require('fs')
  1. Write using fs and format JSON neatly (you don’t even need to create the file beforehand)
try {
  fs.writeFile('./data/output.json', JSON.stringify(<js obj array>, null, 4), (err) => {
        if (err) {
            console.error(err)
            return
        }
    })
}
catch (e) {
    console.error(e)
}