Node.js Tutorial: Introduction for beginners (Basic)

node.js tutorial

Node.js is an open-source server environment. It’s free and runs on various platform such as Windows, Linux, Mac OS X, etc. Node.js was written initially by Ryan Dahl in 2009. It’s written in C, C++, and JavaScript. It can generate dynamic page content, collect form data, manage data in your database, manage files on a server, and etc… In this tutorial. You will learn some basic Node.js programming concepts.

Read First: JavaScript Tutorial : Introduction for beginners (Basic)

Node.js Tutorial – Installation

Vist Node.js official webpage and download “node js setup file” file then install it.

Node.js Tutorial – Start Guide

Create a file named “HelloWorld.js”, you can use any text editor software for this. (Notepad, Visual Studio Code) Then add the following code to display “Hello World”

HelloWorld.js

console.log("Hello Wolrd!");

Open Command Prompt and navigate to the directory where you saved “HelloWorld.js” then enter the
following command and press enter to execute your code.

node HelloWorld.js

Node.js Tutorial – Node Package Manager (NPM)

NPM is an Online repository for node.js packages or modules. you can find NPM modules and packages using www.npmjs.com.

Installing Modules using NPM

Open the command line interface enter following command to install modules and packages.

npm install moduleName

Updating a Module using NPM

Open the command line interface enter following command to update modules and packages.

npm update moduleName

Uninstalling a Module using NPM

Open the command line interface enter following command to uninstall modules and packages.

npm uninstall moduleName

Node.js Tutorial – File System Module

File system module can Read, Create, Update, Delete, Rename files, and etc.

var fsys = require('fs'); //includes

Open a File

fsys.open(path, flags[, mode], callback)

Flags

“r” – Opens a file for reading
“r+” – Opens a file for reading and Writing
“w” – Opens a file for writing (overwrite any existing content or file)
“w+” – Opens a file for writing and Reading (overwrite any existing content or file)
“wx” – Opens a file for writing but fails if the file exists.
“a” – Opens a file for appending (append to the end of the content)
“a+” – Open file for reading and appending. (create a file if the file does not exist)

var fsys = require("fs");

// Opening File
fsys.open('data.txt', 'r', function(err) {
   if (err) throw err;
   console.log("data.txt -> File opened successfully!");     
});

Now execute node.js file

Read Files

fsys.readFile(path, callback)
var fsys = require('fs');

fsys.readFile('newFile.txt',{encoding: 'utf-8'}, function(err, data) {
  if (err) throw err;
  console.log(data)
});

Now execute node.js file

Create Files

fs.open()

fsys.open(path, flags[, mode], callback)

Flags

“r” – Opens a file for reading
“r+” – Opens a file for reading and Writing
“w” – Opens a file for writing (overwrite any existing content or file)
“w+” – Opens a file for writing and Reading (overwrite any existing content or file)
“wx” – Opens a file for writing but fails if the file exists.
“a” – Opens a file for appending (append to the end of the content)
“a+” – Open file for reading and appending. (create a file if the file does not exist)

var fsys = require('fs');

fsys.open('newFile.txt', 'w', function (err, file) {
  if (err) throw err;
  console.log('Saved!');
});

Now execute node.js file

fs.write() -It will create a file if the file does not exist. if the file exists, this method replaces the specified file and content

fsys.writeFile(filename, data[, options], callback)
var fsys = require('fs');

fsys.writeFile('newText.txt', 'Hello World!', function (err) {
  if (err) throw err;
  console.log('newText.txt -> Created!');
});

Now execute node.js file

fs.append() – If the file does not exist, the new file will be created

fsys.appendFile(filename, data[, options], callback)
var fsys = require('fs');

fsys.appendFile('newFile.txt', 'Hello!', function (err) {
  if (err) throw err;
  console.log('newFile.txt -> Created!');
});

Now execute node.js file

Update Files

var fsys = require('fs');

fsys.appendFile('newFile.txt', 'Updated Text', function (err) {
  if (err) throw err;
  console.log('newFile.txt -> Updated!');
});

Now execute node.js file

Rename Files

fsys.rename(oldFileName, newFileName, callback)
var fsys = require('fs');

fsys.rename('newFile.txt', 'renamedNewFile.txt', function (err) {
  if (err) throw err;
  console.log('newFile.txt -> Renamed!');
});

Now execute node.js file

Delete Files

fsys.unlink(path, callback)
var fsys = require('fs');

fsys.unlink('renamedNewFile.txt', function (err) {
  if (err) throw err;
  console.log('newFile.txt -> File deleted!');
});

Now execute node.js file

Create a Directory

fsys.mkdir(path[, mode], callback)
var fsys = require('fs');

fsys.mkdir('newDir/',function(err) {
   if (err) throw err;
   console.log("Directory created successfully!");
});

Now execute node.js file

Read a Directory

fsys.readdir(path, callback)
var fsys = require('fs');

fsys.readdir("newDir/",function(err, files) {
   if (err) throw err;
   files.forEach(function (file) {
      console.log(file);
   });
});

Now execute node.js file

Remove a Directory

fsys.rmdir(path, callback)
var fsys = require('fs');

fsys.rmdir("newDir/Dir1",function(err) {
   if (err) throw err;
   console.log("Directory created successfully!");
});

Now execute node.js file

Node.js Tutorial – HTTP Module

var http = require('http'); //includes

Create a file named “HelloWorldWeb.js”, you can use any text editor software for this. Then add the following code to display “Hello World!” on the Web.

HelloWorldWeb.js

//Includes the module.
var http = require("http");

var hostname = '127.0.0.1';
var port = 8080;

//Create a HTTP Server
var server = http.createServer((req, res) => {
  res.statusCode = 200;  //Add a status code 
  res.setHeader('Content-Type', 'text/plain');  //Add an HTTP header
  res.write('Hello World!'); //write a response
  res.end(); //end the response
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Open Command Prompt and navigate to the directory where you saved “HelloWorldWeb.js” then enter the following command and press enter to execute your code.

node HelloWorldWeb.js

Open your internet browser, and visit: http://localhost:8080 or http://127.0.0.1:8080

HTTP and FS

index.html

<html>
<head>
<title>My First Node.js</title>
</head>

<body>
<h1>Welcome to ctechf.com</h1>
<p>Node.js is an open-source server environment.</p>
</body>

</html>

node_fsyshtml.js

var http = require('http');
var fsys = require('fs');

http.createServer(function (req, res) {
  fsys.readFile('index.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });
}).listen(8080);

console.log('Server running at http://127.0.0.1:8080/');

Now execute js file and visit http://localhost:8080 or http://127.0.0.1:8080

Read the Query String

var http = require('http');
var fsys = require('fs');

http.createServer(function (req, res) {
  fsys.readFile('index.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(req.url);
    console.log(req.url); //url
    res.end();
  });
}).listen(8080);

console.log('Server running at http://127.0.0.1:8080/');

Now execute js file and visit http://localhost:8080/hello or http://127.0.0.1:8080/hello

Node.js Tutorial – URL Module

var http = require('url'); //includes
var http = require('http');
var url = require('url');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    adr = req.url;
    var q = url.parse(adr, true);
    
    console.log(q.pathname);
    res.write('Path Name: '+q.pathname);
    res.write('<br/>');

    console.log(q.search);
    res.write('Search Data: '+q.search);
    res.write('<br/>');

    var urldata = q.query;

    console.log(urldata);

    console.log(urldata.id);
    res.write('id: '+urldata.id);

    res.write('<br/>');
    console.log('');
    res.end();
}).listen(8080);

console.log('Server running at http://127.0.0.1:8080/');

Now execute js file and visit http://localhost:8080/index.html?id=20&name=Niklause
or
http://127.0.0.1:8080/index.html?id=20&name=Niklause

Sources : 
https://pixabay.com/ (images) 

Hello Friends,

Hope this post (Node.js Tutorial: Introduction for beginners (Basic)) will help you to learn something, If you enjoy my work then please share my posts with your friends and anyone who might be interested in web development and don’t forget to subscribe my mailing list.

If you had any problem with this post, please do mention it in the comment section.

Like ctechf Facebook fan page : https://www.facebook.com/ctechf

Best Free eBooks to Learn Python Programming

Free eBooks to Learn Python, Here are 13 of the best Python eBooks for python lovers.
Download Now

What is Python?

Python is a scripting language and that is used for creating engineering-analysis tools, web development (server-side), software development, system scripting, and animation software. It designed by Guido van Rossum and first released in 1991. It’s an interpreted, High-level. General-purpose language. Python runs on Windows, Mac OS, and Linux.

Python Tutorial: Introduction for Beginners (Part 1)
Python Tutorial: Introduction for Beginners (Part 2)
Python Tutorial: How to Connect MySQL Database in Python
Python Tutorial: Python GUI Programming (Tkinter)
Python Tutorial: Send Emails Using Python
Python Tutorial: Django Tutorial for Beginners

How to be a Programmer

Leave a Reply

71 Shares
Share
Tweet
Share
Pin
Share