Learning Journal Node.js: writing to files

Learning Journal Node.js: writing to files

One of the ways to output in Node.js is to write directly to files in the local file system. One method that Node.js provides is fs.writeFileSync. This is a blocking method that appears to write string data to a given file, using the file name as a reference.

The fs.writeFileSync command takes two arguments/parameters:

  1. file name

  2. text string

It requires that the fs (file system) module be imported, and then will write the text string directly to the file name. What's interesting to me about this, however, is that it will also overwrite any existing data that's in the file.

For example:

// app.js
const fs = require('fs')

fs.writeFileSync('notes.txt', 'This was written in Node.js!')

The output of this JavaScript execution is:

  1. The file notes.txt is created as a sibling file to app.js (the code above)

  2. The notes.txt file contains the This was written in Node.js string value

Interestingly, the fs.writeFileSync method will also overwrite any existing data in the file. For example:

// app.js
const fs = require('fs')

const fileName = 'notes.txt'

fs.writeFileSync(fileName, 'This was written in Node.js!')
fs.writeFileSync(fileName, 'My name is Nathan')

The resulting value in notes.txt will only be the My name is Nathan string, rather than This was written in Node.js!My name is Nathan .

If you're trying to continuously write to the file, you should instead use fs.appendFile or fs.appendFileSync so that new values are added to the file, rather than overwriting them.