Menü schliessen
Created: February 12th 2021
Categories: Common Web Development,  IT Development
Author: Marcus Fleuti

NodeJS and NPM Setup with basic example

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Introduction

I am going to explain you step-by-step how to make a easy NodeJS setup & installation.

NodeJS

NodeJS is an open-source runtime environment for developing server-side web applications. It has an event-driven architecture.
Thanks to its non-blocking I/O model is NodeJS lightweight and efficient.

Node Package Module (NPM)

With NPM you can load dependencies easy and efficiently. To load some dependency you just have to enter this command:

npm install

A .json file is getting generated while you are installing dependencies. The file is named package.json and should look like that:

{
  "name": "ApplicationName",
  "version": "0.0.1",
  "description": "Application Description",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/npm/npm.git"
  },
  "dependencies": {
    "express": "~3.0.1",
    "sequelize": "latest",
    "q": "latest",
    "tedious": "latest",
    "angular": "latest",
    "angular-ui-router": "~0.2.11",
    "path": "latest",
    "dat-gui": "latest"
  }
}

Installation of NodeJS and NPM

Firstly you need to install NodeJS on your system. Simply download it and install it right here -> NodeJS

If your installation is successful you can start testing if NodeJS is working. Test this by the following command:

node -v

NPM is getting installed directly with NodeJS, so to test that just type this command:

npm -v

Basic Example

For this example you only need a file called server.js. This file should contain the following code:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer(function(req, res) {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, function() {
  console.log('Server running at http://'+ hostname + ':' + port + '/');
});

We need "http" to create a server instance. For hostname we are using localhost and port can be defined whatever you want.
After that we are creating the Server which sends us an statusCode 200 with the message "Hello World".

Now we can set the server to listen mode and the server is running.