Getting Started with Node Js

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

Getting Started With NodeJs
NodeJs
You need to have install before begin:

  • Download 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 new terminal and type command: 


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

When only npm init command 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 node project like package name, version, description, author, license, keyword, etc. details. Entering in every steps takes default values. However, npm init -y auto fill 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 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 new file hello.js file in project folder using '+' sign in top-left side of terminal. This appears when you hover over project name. In the file write following line of code and save.

hello.js


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

Now, execute the file from the terminal using 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 method console.log().

How to create Server in Node?

Node Server can be created using 'http' core module of Node. Core module of Node need not 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 like  fs, http, path, querystring, url, util, etc. 

Create new file index.js (index file) in project folder using '+' sign in top-left side of terminal. This appears when you hover over 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 server. Listening on unused port. Port number can be saved as variable but for ease for now we simply gives port value to listen 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 web server. when web server works it would prints out  'Server is running at port 3000' i.e. same string you provided in 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 build over NodeJs thus, need to install it before using it in the project. ExpressJs is NodeJs web application framework that helps in  smooth development of server-based application. Here, we are going to create a basic web server in NodeJs using ExpressJs.

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


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

This will create new folder in 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 most efficient way to create 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 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