JavaScript

Synchronously read, write and append files
Read a dir recursively

In this tutorial, we’ll learn how to read, write, and append to files in a asynchronous and synchronous manner. We’re going to write a simple program that grab text from a file, and saves it in a new file. We’ll also learn how to read a dir in a synchronous manner recursively.

  1. The file system
  2. Read file
  3. Write file
  4. Append file
  5. Error handling with synchronous file operations
  6. Read dir / folder
  7. Read dir tree

The file system

First we’ll require our dependencies:

const fs = require('fs')

The fs is the core modules so there’s no need to install this dependency. See documentation: https://nodejs.org/api/fs.html.

Synchronous read file

JavaScript executes in a single threaded event-loop. A long-lasting synchronous operation will delay concurrent logic.

The readFileSync returns raw buffer if character encoding is not specified.

/*Simple sync example*/
const fs = require('fs')
const file = 'path/file.txt'

let data = fs.readFileSync(file)
console.log(data)
//<Buffer 61 62 63 0d 0a 64 65 66 0d...

If the encoding option is specified then readFileSync returns a string:

let data = fs.readFileSync(file,'utf-8')
console.log(data)
//abc def...

Synchronous write file

Next, we’ll write the content to a new file and save:

const newFile = 'path/text.txt'
fs.writeFileSync( newFile, data)

The writeFileSync writes data to a file, replacing the file if it already exists without giving any warning. data can be a string or a buffer.

Synchronous append file

Finally, let’s append some text to previous file so we can keep a record:

let appendTxt = (new Date) + " Text copied to " + newFile
fs.appendFileSync(file, appendTxt)

appendFileSync append data to a file. It creates new file if it if it does not yet exist.

Read, write and append synchronously (complete example)

/*Simple sync example*/

const fs = require('fs')
const file = './abc.txt'

//Read file
let data = fs.readFileSync(file)

//Specify encoding for String output
/*let data = fs.readFileSync(file,'utf-8')*/

//Write data to a file
const newFile = './abcd.txt'
fs.writeFileSync( newFile, data)

//Append some text to previous file
let appendTxt = (new Date) + " Text copied to " + newFile
fs.appendFileSync(file, appendTxt)

Error handling with synchronous file read, write or append

The readFileSync, writeFileSync and appendFileSync throws an error, for example, when a path is not found or file is not accessible. This error is from the Error prototype and thrown using throw, hence the only way to catch is with a try / catch block:

/*Simple sync example*/
const fs = require('fs')
const file = 'path/file.txt'

let data
try {
 data = fs.readFileSync(file)
 console.log(data)
} catch (err) {
 // Here you get the errors
}

Synchronously read dir / folder

The Node.js implementation of readdirSync is a simple command to read a directory.  It is the synchronous implementation of the file-system directory read:

let files = fs.readdirSync('./')
files.forEach(entry => { 
 console.log (entry)
})

This will print all files and folder from the given path on command terminal.

Synchronously read dir tree (recursive operation)

 

const fs = require('fs')
const path = require('path')
 
function readTree (entry) {
 let stat = fs.lstatSync(entry)
 if (stat.isDirectory()){
  let files = fs.readdirSync(entry)
  files.forEach( file => {
   readTree(path.join(entry,file))
  })
 } else {
  console.log (entry)
 }
}

readTree (path/of/dir)

The path.join method is a useful utility that normalizes paths across platforms, since Windows uses back slashes \ whilst others use forward slashes / to denote path segments.

A lstatSync provides information about the path which store in stat variable.

stat.isDirectory() return true if the given path is a directory.