When should I use this? A look into the various functions of the Node.js file system.

Photo by Temple Cerulean on Unsplash

It doesn’t take more than a minute to notice duplicated functions name among what is mentioned in the Node.js file system documentation. Did the writer seriously not realize such blatant repetition? fs.mkdir(path[, options], callback), fs.mkdirSync(path[, options]

Or, upon a second glance, these are all totally different! This realization, like all great ones, leaves us with more questions than what we started with. Let’s start with the base, what do these specific functions do? According to the Node File System documentation it is really quite simple: they create a directory.

Alright, that is great and all but why do we need two? Well, the difference lies in the Sync (or lack of) portion of the name. All this means is that fs.mkdir(…) is a asynchronous function. This means that it operates independently from other processes. More importantly, it can tell us when it’s done! fs.mkdirSync(…) sadly will leave us in the dark as to its current status. Here’s an example:

var fs = require('fs')
function printSomething() {
console.log('Created a directory!')
//Sync version of the function
fs.mkdir('./cool_new_folder', 0o776, (err) => {
if (err) console.log(err)
else printSomething()
//Async version
fs.mkdirSync('./cool_new_folder2', 0o776); 

Note that when using the asynchronous version of the function we are able to provide an if-else statement based on an error or not. Take into consideration that this is only done once the function returns a value of unknown, indicating that it is finished. In this specific example we aren’t taking much advantage of this. But think of the possibility of wanting to create a file within this new directory. If you were to use the mkdirSync version of the function, it is very possible that your program tries creating this file before the folder has even been created, resulting in an error.

Have a look behind the scenes at the git repository.

This sync vs async idea can apply to many of the functions in this repository but also in others throughout the web as well. I do hope very much that this simple, but important information can prove valuable in the future!