Getting Started with Node Js

NodeJs is an open source cross-platform, javascript runtime environment for servers and environments. Chrome's V8 JavaScript are building blocks which parses and executes JavaScript code.  NodeJs is a widely used programming model.

Getting Started With NodeJs
NodeJs
You need to have installed before beginning:

  • Download the Latest (LTS- Long Term Support) Version of Node from NodeJs.
  • Download Visual Studio Code (VS Code) as an Editor (recommended) from VS Code.

Create new folder for your project naming project name. Open the folder in VS Code. Then, open a new terminal and type the command: 


    Amrit@devkota MINGW64 ~/Desktop/node_basics
    $ npm init -y

When only npm init command is applied,


    Amrit@devkota MINGW64 ~/Desktop/node_basics
    $ npm init
    This utility will walk you through creating a package.json file.
    It only covers the most common items, and tries to guess sensible defaults.

    See `npm help init` for definitive documentation on these fields
    and exactly what they do.

    Use `npm install <pkg>` afterwards to install a package and
    save it as a dependency in the package.json file.

    Press ^C at any time to quit.
    package name: (node_basics)
    version: (1.0.0)
    description:
    entry point: (index.js)
    test command:
    git repository:
    keywords:
    author:
    license: (ISC)
    About to write to C:\Users\Amrit\Desktop\node_basics\package.json:

    {
    "name": "basics",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC"
    }


    Is this OK? (yes) y

you have to fillup every information about the node project like the package name, version, description, author, license, keyword, etc. details. Entering every step takes default values. However, npm init -y auto fills all information needed setting to default values at once. If you like you could edit them on package.json file formed after this command. This creates a package.json file. This file is the main file of any Node project. It's hold metadata of the project that defines functional attributes to install dependencies and to run script.


How to write your first program (Hello World) in NodeJs?

Create a new file hello.js file in the project folder using the '+' sign on the top-left side of the VS Code. This appears when you hover over the project name. In the file write the following line of code and save.

hello.js


    console.log('Hello World! from NodeJs!')

Now, execute the file from the terminal using the command: either node hello.js or node hello without .js file extension.


    Amrit@devkota MINGW64 ~/Desktop/node_basics
    $ node hello.js
    Hello World! from NodeJs!
   

The result is shown right below the command. It prints the string statement given inside the method console.log().

How to create a Server in Node?

Node Server can be created using 'http' core module of Node. The core module of Node need not be required to install in every project as they already came up with Node. Only importing the module works totally fine. Some important core modules are fs, http, path, querystring, url, util, etc. 

Create new file index.js (index file) in the project folder using the '+' sign on top-left side of VS Code Window. This appears when you hover over the project name.

In the index file, we import http module using require method. To import the package, write; const http = require('http'); line of code in line 1. createServer method of http is used to create a server. Listening on an unused port. The port number can be saved as a variable but for ease, for now, we simply give the port value to listen to method.


index.js


    const http = require('http');

    const server = http.createServer(function (req, res) {

        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Hello World from Node Server');

    });

    server.listen(3000, () => {
        console.log('Server is running at port 3000')
    });

Now, execute the file using node index.js from the terminal to run the web server. when the web server works it would print out  'Server is running at port 3000' i.e. same string you provided in the log method. Visit localhost:3000 to see the response 'Hello World from Node Server' same as you set in res.end method in index.js.


    Amrit@devkota MINGW64 ~/Desktop/node_basics
    $ node index.js
    Server is running at port 3000


How to create Node Server using ExpressJs?

Express is a third-party package/module built over NodeJs thus, need to install it before using it in the project. ExpressJs is NodeJs web application framework that helps in the smooth development of the server-based applications. Here, we are going to create a basic web server in NodeJs using ExpressJs.

Node application depends on various modules and packages, that we install and import before using them in the application. Installation is required for third-party packages only. We here install each required package once it's needed! The first essential package is express. So, in the terminal of VS Code in the project directory we download express using the code below.


    Amrit@devkota MINGW64 ~/Desktop/node_basics
    $ npm install express

This will create a new folder in the project directory 'node_modules' that contains all the packages you install and their dependencies packages. For now, you get sub-folders of express and its dependencies.

In the index file we remove all previous content, then we import express using require method. To import the package, write; const express = require('express'); line of code in line 1. Few line of codes is sufficient to create a server. It's the most efficient way to create a server using express.


index.js


    const express = require('express');

    const app = express()

    app.get('/', (req, res) => {
        res.send('Home page');
    })

    app.listen(3000);

    console.log('Server is started and listening at port 3000')

To run the web server in the terminal execute the file node index.js and visit http://localhost:3000 you get the response 'Home page' in web-page and 'Server is started and listening at port 3000' in VS Code terminal right after the command: node index.js.


    Amrit@devkota MINGW64 ~/Desktop/node_basics
    $ node index.js
    Server is started and listening at port 3000








0 Comments