File System

The fs module provides an API for interacting with the file system. To use this module:

const fs = require('fs');

Synchronous vs Asynchronous Form

Every method in the fs module has synchronous as well as asynchronous forms. Asynchronous methods take the last parameter as the completion function callback and the first parameter of the callback function as error. It is better to use an asynchronous method instead of a synchronous method, as the former never blocks a program during its execution, whereas the synchronous form does.

Create a Directory

fs.mkdir(path[, mode], callback);

Here, path is the directory name including path. mode is the directory permission to be set. Defaults to 0777. The last argument is a callback which is called when the execution is finished.

let fs = require("fs");
function createFolder(folderName){
	fs.mkdir("./"+folderName, function(error){
		if(error == null){
			console.log("Folder Created Successfully ");
		}else{
			console.log("Cannot Create Folder : "+folderName);
			if(error.code == "EEXIST"){
				console.log("Folder Already Exists !");
			}else{
				console.log("Unknown Error !");
			}
		}
	});
}
createFolder("img");

The last callback function is called after the execution of mkdir. This callback receives an error object. If the folder is created successfully then the error object is null, otherwise it contains the error object.