KickStart to NodeJS

KickStart to NodeJS

Global objects, Filesystems, Modules and directories, Streams and piping.

ยท

3 min read

Let's see a JavaScript runtime which allows us to run the scripts outside of a browser.

TL;DR

JavaScript is ofcourse the de-facto language of browser, and these browser has javascript engine built in, for example google has v8 engine, firefox has SpiderMonkey and as such for major browser's out there. But seeing the constraint of JavaScript just for browser NodeJS comes up with a solution of a platform built on top of v8 engine. NodeJS is a C++ program that leverages javaScripts ability to run on a machine.

NodeJS

As javascript can now run on a machine despite a browser, we can have a limited access of system configures as of Java or C++.

Mainly NodeJS is used for non-blocking, single-threaded, event based servers. Used in traditional web sites and back-end API services. Optimal for realtime events and not encouraged for cpu intensive operations

Download the latest node.js source code before proceeding.

After installing make sure it's properly available on your system by, opening command promt and:

node -v
//outputs the version eg: v12.13.0

Basics

Let's kickstart into the basics, some of them are filesystems and OS configures.

Know that nodejs is javascript on its core so all the variables, functions, datastructures, objects works as such fine. For compiling a nodejs code

node *your_file_name*
  • Global Object

Similar to window object in browsers while using javascript, which has builtin properties to used.

global.setTimeout(()=>{},1000);
global.setInterval(()=>{},2000);

We don't actually explicitly define global.

  • Modules

Rather than writing the whole code on a single file we split into modules and get the using the require keyword.

Which eventually makes our code modular, readable, reuseable, and easy to maintain.

data.js

const dataNumbers=[1,2,3,4,5];
module.exports=data;  //ready to be required by other files

displayModule.js

const myData=require('./data');
console.log(myData);  //outputs [1,2,3,4,5]

We can too export multiple data from a single files as:

data.js

const names=["Nick","Sarath","Leah"];
const numbers=[1,2,3,4,5];

module.exports={
names,
numbers
}

displayModule.js

const myData=require('./data');   //destructuring the properties here is more readable

console.log(myData.names);  //outputs ["Nick","Sarath","Leah"]
console.log(myData.numbers); //outputs [1,2,3,4,5]
  • Filesystems and Directories

Read, write, delete and update files in system using nodeJS.

const files = require('fs');   /*fs is a global module*/

//READ FILE
files.readFile('./file.txt', (err, data) => {
 try {
     console.log(data.toString());
      } catch (err) {
      console.log(err);
      }
});


//WRITE FILES
files.writeFile('./file.txt', 'HELLO NINJA', () => {
  console.log("FILE written");
});
files.writeFile('./dynamicfile.txt', 'HELLO CODE', () => {
  console.log("DYNAMIC FILE written");
});


//DIRECTORIES
if (!files.existsSync('./assets')) {  //if ain;t existsing creates a directory
 files.mkdir('./assets', (error) => {
     error ? console.log(error) : console.log("created");
 })
 } else {   //if already exists deletes the directory 
 files.rmdir('./assets', (error) => {
   if (error) {
      console.log(error);
    }
    console.log("deleted");
   })
}

//DELETE FILES
if (files.existsSync('./deleteme.txt')) {
  files.unlink('./deleteme.txt', (err) => {
     if (err) {
      console.log(err);
     }
     console.log("removed");
   });
}
  • Streams and Piping

So the above mentioned approach of filesystem may be tedious for large datasets, so that we go for streams which provide a faster and efficient approach for the same.

const fs = require('fs');

const readLarge = fs.createReadStream('./large.htm', { encoding: 'utf8' }); //reads the whole data
const writeLarge = fs.createWriteStream('./largewritepipe.htm'); //writes the whole data

// PIPING
readLarge.pipe(writeLarge);

Major Takeaway

NodeJS clears a way for javaScript to reign the territory of web development, by successfully compiling the code out of browser's.

Let's connect ๐Ÿ”—

Catch me here ๐Ÿ‘‡


Hope you all liked the post, share your impressions and queries below ๐Ÿ™Œ

ย