Writing Files with Node.js

Writing Files

  1. Import fs module (native to Node, no need to install from NPM)

    const fs = require('fs')
  2. 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)
    }