TitBits of Node.js

📄 Table of contents

➤ why nodeJS is NOT a Framework

  • NPM
  • Modules

nodeJS callbacks

  • writing Custom Callbacks

nodemon

simplest ever Server using “http” module

simplest ever Server using “expressJS” framework

➤ how to server Static files in nodeJS.

How to create a REST API with Express.js and Node.js

Building a Node.js API using nodeJS + Express + MongoDB

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ ✦ ✦ ✦ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

◉ all about nodeJS

  • First of all, NodeJS is NOT a framework.
  • Node.js uses Asynchronous programming!
  • Node.js applications simply output the data in chunks and never buffer any data.
  • Node.js runs single-threaded, non-blocking, ASYNCchronously programming, which is very memory efficient.
  • It can run Javascript outside the browser. Basically, It is Javascript running on the server.
  • It is built on Chrome’s V8 Javascript engine and V8 is written in C++.
  • works on a single thread using non-blocking I/O calls.
  • supports tens of thousands of concurrent connections.
  • Node.js is an open source server environment.
  • Node.js is Cross-platform framework that runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • Node.js implements CommonJS modules standard.
  • Node.js files have extension “.js”

◉ Why is nodeJS NOT considered a Framework ?

  • Node.js includes that interpreter separately which requires to execute code. It takes this power from the chrome v8 engine which is used in chrome to run JavaScript. And, it extends the power of handling file and network I/O with a preference for asynchronous patterns. In simple words, we can do a lot of things in NodeJS which are not possible with JavaScript like network I/O, File handling, etc. For security reasons, JavaScript originally did not include file I/O for use in the browser. And, it did not need to do networking tasks, because the browser does them. JavaScript was built out with the DOM for the browser.

In simple words,
The engine is a collection of the compiler and the interpreter used to run a language on a platform as JavaScript run by v8 engine on chrome.

So, the original idea of node.js was to be able to set up a web service or a TCP server really fast. You could, and still can, just copy a code snippet, put it in a js file and then run it with node, and you will have a server. Yeeee!

At last,
Node.js (Node) is not a framework nor a language but a run time open source development platform for executing JavaScript code server-side.

◉ What is NPM?

  • NPM is a package manager for Node.js packages, or modules if you like.
  • It is the largest ecosystem of open source libraries in the world.
  • The NPM program is installed (by default) on your computer when you install Node.js.
  • Once you have downloaded and installed your first package say : “xyz” using npm install xyz, NPM creates a folder named “node_modules”, where the package xyz will be placed. All packages you install in the future will be placed in this folder.

Modules in NodeJS?

Consider modules to be the same as JavaScript libraries.

To include a module, use the require() function with the name of the module:

var http = require(‘http’);
var express = require('express');
var fs = require('fs');

You can create your own custom module just like inbuilt module.

◉ Callbacks in nodeJS

Node JS handle all Asynchronous calls via callback. Hey wait, what is callback..?? well, callbacks in the general definition are just functions that you pass to other functions. It is called at the completion of certain task.

doesn’t make any sense..!! function passing to another function…!! what’s going on here..?? let me give a simple example of callback

fs module is built-in module of Node JS which is used to work with file system of your computer .Here i’m using fs.stat() function to get file information of input.txt which give information about file size, created date, last modified date, bla bla.. bla bla…

Let’s analyse how this code snippet is working. Here we can see that fs.stat()function is taking two arguments. First argument is the path of the file and second argument is a function, which is nothing but a callback function.

Let’s get into more details of code. First fs.stat()will try to find whether the file exists or not, then it will try to get all information about that file. If it successfully get all information then that data is passed into statparameter of callback function. If some error happen in the process, that error is passed into errparameter of callback function. After dealing with the path, callback function get invoked.

Note : According to coding convention of Node JS, the first argument in callback function is for an error object and second argument is for a successful response

If you are making your own custom callback function, it is advisable to follow the same rules.

Here we define a function with two parameters

  1. arg: any argument you pass
  2. Callback : a callback function, and assign that function to a constant variable checkFileType.

Now we are calling the function from line 8 with the help of checkFileType which takes two parameters:

  1. 15 which is a number and
  2. A callback function

That’s a simple example of custom callback.

◉ A Simple NodeJS server (without Express JS)

The code tells the computer to write “Hello World!” if anyone (e.g. a web browser) tries to access your computer on port 3000/8000/etc.

Creating Simplest server using “http” module

here, “http” is the built in module of Node JS through which we can transfer data over HTTP protocols. here is the list of all the built-in modules of Node JS https://nodejs.org/dist/latest-v8.x/docs/api/

Have you notice that if you hit any other localhost urls apart from http://localhost:3000/ it is also showing “hello world”. e.g: http://localhost:3000/about , http://localhost:3000/contact . Naah.. this is not what you want, right..??

let’s add some routing to our app.js:

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var url = req.url;
if(url ==='/about'){
res.write('<h1>about us page<h1>');
res.end();
}
else if(url ==='/contact'){
res.write('<h1>contact us page<h1>');
res.end();
}
else{
res.write('<h1>Hello World!<h1>');
res.end();
}}).listen(3000, function(){
console.log("server start at port 3000");
//the server object listens on port 3000
});

Now again start server and check
http://localhost:3000/,
http://localhost:3000/about ,
http://localhost:3000/contact

nodemon

While doing development on any NodeJS application, whenever we make any change to some file, every-time we need to restart our Node server from the command prompt/terminal. This is a repetitive process since we make hundred of changes and restart the server every time to check the change.

The solution to this issue is using a tool called nodemon. It will continuously check your files for any changes and will restart the server itself if it detects any change.

nodemon can be installed using the following command.

npm install nodemon -g

After the successful installation you can use nodemon app.js (you file name) rather than node app.js in your command prompt and it will keep monitoring files for any change.

but still you need to refresh the “Browser” to see changes being reflected in browser.

What is ExpressJS?

Express is a really cool Node framework that’s designed to help JavaScript developers create servers really quickly. NodeJS may be server side, but it can do a whole lot more than just serve pages and data. NodeJS is a powerful platform that lets you run JavaScript on your shell similar to how you’d run Python.

Express.js is a Node js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications and for creating servers.

ExpressJS is based on the Node.js middleware module called connect which in turn uses http module. So, any middleware which is based on connect will also work with Express.js.

It has become the standard server framework for node.js. Express is the backend part of something known as the MEAN stack.

The MEAN is a free and open-source JavaScript software stack for building dynamic web sites and web applications which has the following components;

1) MongoDB — The standard NoSQL database

2) Express.js — The default web applications framework

3) Angular.js — The JavaScript MVC framework used for web applications

4) Node.js — Framework used for scalable server-side and networking applications.

The MEAN Stack would be a great model to learn with, although I must admit it is more of preference. The best thing about the MEAN Stack is the use of JavaScript syntax across your entire product, from frontend, backend to even the database. MongoDB saves data in BJSON which looks strikingly identical to JSON making it super easy to learn. If you choose to learn the MEAN Stack, here is a great article I made that get you started in a couple of minutes.

The Express.js framework makes it very easy to develop an application which can be used to handle multiple types of requests like the GET, PUT, and POST and DELETE requests.

◉ Building a simple REST API with NodeJS and Express.

If you’re been building apps using HTML, CSS and JavaScript, you may want to learn how to build servers that serve content to these front end technologies.

First, you’ll need to understand the difference between serving static assets and serving data. Serving static files is serving your HTML, CSS and JavaScript pages as they are. The reason they’re called static files is because they are not changed by the server nor run, they’re merely sent back as files for your browser to parse through. This is what you’ve most probably been doing without even realizing.

Express is a really cool Node framework that’s designed to help JavaScript developers create SERVERS really quickly.

Pre-Requisites

download the most stable release of NodeJS.
Open cmd => check for
npm -v
node -v
to confirm that above installation has been successful

type npm init to interactively create your package.json file.The package.json describes the app. It is very important. When uploading your app, your dependencies will be listed avoiding duplication and excessive data transfer.

npm install express — save

The -g flags specifies that you’re installing the module globally to use anywhere within your computer. Not using the -g flag will install the tool/module into that specific folder and will not be available outside that scope.

var express = require(“express”);
var app = express();
app.listen(3000, () => {
console.log(“Server is running on port 3000”);
});

Congrats! You just made your first useless express server above! Let’s start implementing the REST protocol now.

A server receives requests, processes them and returns a response. So you need to use routes to handle this requests. The requests have three major types, a GET request that get’s data, a POST request that sends data securely, a PUT request that updates data and a DELETE request that deletes data.

save above as app.js and run as

node app.js

This is what your cmd should look like after running this command.

This means our app is now successfully running on port 3000. To view our data, open up your browser and enter http://localhost:3000/url. You’ll see json data of an array of strings on your browser.

How it all fits as a REST based API.

You might be wondering where the REST attribute comes in. REST stands for REpresentational State Transfer. This means there is no state between the client and the server. There are no webpages served to be parsed, just data. And this gives you all the freedom you need. All you need to do is write some logic on a specific URL that connects to a database, uses it’s logic to process the data and return it in JSON format. Your client can now be an Android app made in Java, or a Windows desktop app made in C# or an Arduino project.

This is the whole point of using REST, it makes the connection stateless therefore any client that utilizes the HTTP protocol can access this data. Now you can iterate through the data and display it anywhere you want.

Unbelievable as it seems, this is a basic REST based API. You make a request to a specific endpoint and get data back in a stateless manner. Very simply put. No complexity here. This is the most basic API you’ll need to do to understand how REST APIs work. In next tutorials, we will learn how to connect to a database, query data and return the data using REST protocol.

for more read @ How to create a REST API with Express.js and Node.js

◉ how to server Static files in nodeJS.

create a Public folder inside root folder and place all .css files inside this folder.

app.use();

Building a Node.js API using nodeJS + Express + MongoDB

refer this link.

What Is Better Node JS Or Angular JS?

Both NodeJS and AngularJS platforms are targeted at building web applications using JavaScript. However, both of them are different in their architecture and working.

NodeJS mainly used to build server-side applications.

AngularJS is suited for building single-page client-side web applications.

These two frameworks are high performing, advanced and widely used worldwide. So one should select according to his/her project need.

NW.js (formerly node-webkit)

You can write desktop apps using websites (HTML, CSS, JavaScript) while retaining access to all Node.JS features and APIs.

Quoting its readme on GitHub:

NW.js is an app runtime based on Chromium and node.js . You can write native apps in HTML and JavaScript with NW.js. It also lets you call Node.js modules directly from the DOM and enables a new way of writing native applications with all Web technologies.

Features (also quoting from the readme):

  • Apps written in modern HTML5, CSS3, JS and WebGL.
  • Complete support for Node.js APIs and all its third party modules.
  • Good performance: Node and WebKit runs in the same thread: Function calls are made straightforward; objects are in the same heap and can just reference each other;
  • Easy to package and distribute apps.
  • Available on Linux, Mac OSX and Windows

There are few options for writing GUI apps in Node:

Remember, authentication is the act of logging a user in. Authorization is the act of verifying the access rights of a user to interact with a resource.

Middleware functions are used as bridges between some pieces of code. When used in the function chain of an endpoint they can be incredibly useful in authorization and error handling.

--

--

--

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

VideoJS / Udemy play videos or movies at custom speed or faster using attribute playbackRate

How to hot-reload with Webpack?

Celebrating Black History Month With a Swahili Programming Language

https://www.amazon.com/s?k=portable+coffee+maker&me=A3V2UP33JI3OTA&rh=p_78%3AB01N7853IC&tag=zoganic-

A journey from Callbacks to Async Await in JavaScript

JavaScript loops comparison and performance

Move to the Right, and then the Left, Maybe

A Simplistic Approach to implement Multi-Tenancy in Node.js

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anil Kumar

Anil Kumar

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

More from Medium

NodeJS and MySQL 8 Connection Issue — Resolved

Setting up node express project

How to use Nodemon in Loopback 4 NodeJs Project