Files and paths
The Node fs module
A guide to the Node.js fs module and its methods for working with the file system, from readFile and writeFile to rename, plus their blocking Sync versions.
The fs module gives you access to the file system. You do not install it. It is part of Node core:
const fs = require('fs')
Once you require it, you get dozens of methods, including:
fs.access(): check if the file exists and Node can access it with its permissionsfs.appendFile(): append data to a file. If the file does not exist, it’s createdfs.chmod(): change the permissions of a file specified by the filename passed. Related:fs.lchmod(),fs.fchmod()fs.chown(): change the owner and group of a file specified by the filename passed. Related:fs.fchown(),fs.lchown()fs.close(): close a file descriptorfs.copyFile(): copies a filefs.createReadStream(): create a readable file streamfs.createWriteStream(): create a writable file streamfs.link(): create a new hard link to a filefs.mkdir(): create a new folderfs.mkdtemp(): create a temporary directoryfs.open(): set the file modefs.readdir(): read the contents of a directoryfs.readFile(): read the content of a file. Related:fs.read()fs.readlink(): read the value of a symbolic linkfs.realpath(): resolve relative file path pointers (.,..) to the full pathfs.rename(): rename a file or folderfs.rmdir(): remove a folderfs.stat(): returns the status of the file identified by the filename passed. Related:fs.fstat(),fs.lstat()fs.symlink(): create a new symbolic link to a filefs.truncate(): truncate to the specified length the file identified by the filename passed. Related:fs.ftruncate()fs.unlink(): remove a file or a symbolic linkfs.unwatchFile(): stop watching for changes on a filefs.utimes(): change the timestamp of the file identified by the filename passed. Related:fs.futimes()fs.watchFile(): start watching for changes on a file. Related:fs.watch()fs.writeFile(): write data to a file. Related:fs.write()
One peculiar thing about fs: every method is asynchronous by default, but you can also call a synchronous version by appending Sync:
fs.rename()fs.renameSync()fs.write()fs.writeSync()
That choice has a huge impact on your application flow.
Node 10 includes experimental support for a promise based API
Let’s look at fs.rename(). The asynchronous API takes a callback:
const fs = require('fs')
fs.rename('before.json', 'after.json', (err) => {
if (err) {
return console.error(err)
}
//done
})
The synchronous version uses try/catch:
const fs = require('fs')
try {
fs.renameSync('before.json', 'after.json')
//done
} catch (err) {
console.error(err)
}
The key difference: in the second example, your script blocks until the file operation finishes.
Lesson completed