Use folders in Node

How to use Node to interact with folders

Node.jsfsThe core module provides many convenient methods that can be used to process folders.

Check if the folder exists

usefs.access()Check if the folder exists and Node can access it with its permissions.

Create a new folder

usefs.mkdir()orfs.mkdirSync()Create a new folder.

const fs = require('fs')

const folderName = ‘/Users/flavio/test’

try { if (!fs.existsSync(dir)){ fs.mkdirSync(dir) } } catch (err) { console.error(err) }

Read the contents of the directory

usefs.readdir()orfs.readdirSyncRead the contents of the directory.

This code reads the contents of folders, files and subfolders, and returns their relative paths:

const fs = require('fs')
const path = require('path')

const folderPath = ‘/Users/flavio’

fs.readdirSync(folderPath)

You can get the full path:

fs.readdirSync(folderPath).map(fileName => {
  return path.join(folderPath, fileName)
}

You can also filter the results to return only files and exclude folders:

const isFile = fileName => {
  return fs.lstatSync(fileName).isFile()
}

fs.readdirSync(folderPath).map(fileName => { return path.join(folderPath, fileName) }).filter(isFile)

Rename folder

usefs.rename()orfs.renameSync()Rename the folder. The first parameter is the current path, and the second parameter is the new path:

const fs = require('fs')

fs.rename(’/Users/flavio’, ‘/Users/roger’, err => { if (err) { console.error(err) return } //done })

fs.renameSync()Is the synchronous version:

const fs = require('fs')

try { fs.renameSync(’/Users/flavio’, ‘/Users/roger’) } catch (err) { console.error(err) }

Remove folder

usefs.rmdir()orfs.rmdirSync()Delete the folder.

Deleting a folder with content may be more complicated than you need.

In this case, I suggest you installfs-extraModule, this module is very popular and well maintained, it is a direct replacement for this modulefsModule to provide more functions on top of it.

under these circumstancesremove()The method is what you want.

Install using

npm install fs-extra

And use it like this:

const fs = require('fs-extra')

const folder = ‘/Users/flavio’

fs.remove(folder, err => { console.error(err) })

It can also be used with promises:

fs.remove(folder).then(() => {
  //done
}).catch(err => {
  console.error(err)
})

Or use async / await:

async function removeFolder(folder) {
  try {
    await fs.remove(folder)
    //done
  } catch (err) {
    console.error(err)
  }
}

const folder = ‘/Users/flavio’ removeFolder(folder)

Download mine for freeNode.js manual


More node tutorials: