Node.js and fs
Node.js provides a general programming environment that utilizes JavaScript to perform logical operations. This allows a web development to be done entirely in JavaScript instead of needing extra languages to perform back-end processes and services.
fs is a module in node.js that allows file system operation. This expands the functionality of JavaScript from mere browser language to something that can interact with the file system of the OS.
Promises, Promises
fs module traditionally used call-back function for its async operations. It has recently introduced Promise object alternatives for more robust programming. Promise object allows easy-to-read chaining of code to address the success or fail state of the given function, among many of its advantages.
Practical example - link(2)
We will be using link as an example. Link creates hard-links of the existing files. We will assume the following directory structure:
./
- file1
- file2
- file3
Using the call-back async method, we can create a hard link file from file1 to file.callback as follows:
const fs = require('fs');
fs.link('file1','file.callback',
(err)=>{
if(err) console.log("ERROR OCCURED: ",err);
console.log("File Link Success");
}
);
In contrast, if I want to use the Promise method, the code would look like the following:
const fs = require('fs').promises;
fs.link('file2','file.promise')
.then( ()=>{console.log("File Link Success");} )
.catch((err)=>{console.log("ERROR OCCURED: ",err)
;
Code is more legible using the Promise object, and the error checking is done internally rather than relying on call-back.
Comments
Post a Comment