Node.js is very popular, and it keeps expanding.
There are so many powerful websites built on this; there is a bloom in Node.js development companies to support that.
How can you start learning Node.js from scratch?
Well, this tutorial will teach you that. You can learn Node.js step by step, starting from the beginning. Therefore, you should not be concerned if you are new to Node.js.
Let's start.
What is Node.js?
JavaScript is used to create the open-source, cross-platform runtime environment known as Node.js.
It is based on the V8 JavaScript engine in Chrome, which runs and parses JavaScript code. One of the critical reasons Node has become so popular is because of this programming paradigm.
Because of its event-driven, non-blocking I/O approach, Node is quick and light.
Building software and services like chat apps and webpages that need synchronous, real-time interactions are best suited for Node.
But it also has other uses and benefits that developers like, which makes it even more popular.
Benefits of Learning Node.js
Consider learning Node.js if you have an interest in back-end or front-end development.
Here are five excellent reasons:
1. Easy to Understand
JavaScript is the language used to create Node.js. Nearly all developers are familiar with JavaScript, one of the most widely used programming languages. Therefore, even a beginner JavaScript coder may learn Node with less time and effort.
2. Full Stack js
Node.js is responsible for the growth of full-stack web development. This is called full stack web development, when a single developer handles all facets of a program, including front-end development, back-end development, database administration, etc.
Full stack developers had to master several languages before Node. Writing front-end and back-end web apps using Node requires a working knowledge of JavaScript.
3. Market Demand
There is a significant need for full-stack developers, and increasing job positions call for knowledge of Node.js. So, including Node.js in your CV is a smart move to increase your possibilities for employment as a stack developer.
4. App Development Freedom
Node offers more freedom when creating apps than Ruby on Rails, which imposes limits and regulations on Node.js development companies. A brand-new Node installation provides the necessities, letting you create anything from scratch with little limitations.
5. Active Community
Developers who regularly contribute to its advancement make up the active and lively community supporting the open-source framework Node.js. That makes learning simpler because many options are available at every developmental level.
You can scroll down to learn Node.js systematically if you believe it will be your next step in advancing your career.
1. Node.js Installation
Follow these instructions step by step to install Node.js:
1. Visit the official website at https://nodejs.org/en/ to download Node.js.
2. Then install it like any other application.
3. Open a Command Prompt to verify that Node.js is already installed on your PC.
4. Next, enter the following command:
5. Next, run the following command to update npm.
2. The web server in Node.js
Let's create a simple web application that, in response to a user request, displays the phrase "Hello World."
const http = require ('http');
const hostname = 'localhost';
const port = 3000;
const server = http.createServer ((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end ('Hello World ');
});
server.listen (port, hostname, () => {
console.log (`Server running at http ://${ hostname} :${ port}/`);
});
1. In a new file, copy and paste it. Save the file with the name hello.js.
2. Open your terminal and navigate to the folder containing the file before running this code.
3. To run your code, type this command.
4.The following message should be on the terminal.
5. Type localhost: 3000 into your browser and hit enter. You should see the message below.
3. Node modules
The main building block of the Node program is the Node module.
A node module is a group of functions that can be used repeatedly in your app. Node has modules that come with it, and you can make your own.
Some well-known built-in node modules are fs, net, and HTTP, and popular modules like Express and nodemailer are built on top of these.
The node package manager, or npm, lets us put node modules in place.
The following command can be used to install node modules.
Open the terminal or command prompt and type this command into it.
You can even design your node modules. All you have to do to make a function reusable is export it.
Package.json is the file that controls Node modules. This file includes a list of your project's packages and information such as the version number.
4. Express Installation
Express is a simple and adaptable Node.js application framework that gives web and cellular apps a wide range of advanced features.
Express has a lot of HTTP utility methods and middleware that you need, which makes it easy and quick to build a robust API.
It might sound complex, but it's not really.
Before we install express, we need to make a file called package.json in our project.
To make package.json, all you have to do is type the following command into the Node.js terminal.
The above command will automatically make the package.json file for your project.
After that, you can install express.
To install express, enter the command in the terminal Node.js.
Express Routing
Express makes it easy for Node.js applications to define routes.
Here we take two routes, namely home and about.
Where the home route shows "Welcome to Express" and the about route shows "This is the about page."
Alright, let's get started.
1. Open the hello.js file you already made, and then change it to look like this:
const express = require('express');
const app = express();
//route for home page
app.get('/',(req, res) => {
res.send('Welcome To Express');
});
//route for about page
app.get('/about',(req, res) => {
res.send('This is about page');
});
app.listen(8000, () => {
console.log('Server is running at port 8000');
});
2. Type the following command into the terminal to run hello.js:
3. Enter the following URL into your browser:
4. The result will then appear as follows:
Output
localhost:8000
Welcome To Express
5. Then enter the following URL to show the "about" page:
6. The result will then show as follows:
Output -
localhost:8000/about
This is about page
5. File System Module
The fs module offers an API for working with your operating system's file system. This module must be required in your code.
This node module includes many methods for carrying out many operations, including creating files, writing data into files, reading data from files, etc.
To read files in Node, use the fs.readFile() or fs.readFileSync() methods.
1. Using the readFile() method,
const fs = require('fs');
fs.readFile('./lorem.txt', (err, data) => {
if(err) {
return console.log('Error occurred while reading file');
}
console.log(data.toString());
});
2.The readFileSync() method
const fs = require('fs');
const data = fs.readFileSync('./lorem.txt'); console.log(data.toString());
The readFile() function is the simplest way to determine whether a file exists.
The file descriptor is opened by this function, though, and it also uses some memory.
We strongly advise using the access() function if all you want to do is verify that a file is present on the system.
This is the code:
const fs = require('fs');
const path = './config.js';
fs.access(path, fs.F_OK, (err) => {
if (err) {
console.error(err);
return;
}
});
There are three ways to create files using the file system module:
● fs.open()
● fs.appendFile()
● fs.writeFile()
If a file does not exist in the supplied directory, the fs.open() method creates a new empty file or opens a new file.
The second argument is used as a flag and can be anything from w for writing to w+ for reading and writing, etc.
Code:
const fs = require('fs');
fs.open('file.txt', 'w', (err, file) => {
if (err) {
throw err;
}
console.log('Saved!');
});
You can create or replace existing files with the content using the fs.writeFile() method.
If a file already exists, the specified content will be used to replace it; otherwise, a new file will be created.
const fs = require('fs');
const fs = require('fs');
fs.writeFile('file.txt', 'Hello Word!', (err) => {
if (err) {
throw err;
}
console.log('Saved!');
});
The fs.appendFile() method appends the supplied content to the end of the file.
const fs = require('fs');
fs.appendFile('file.txt', ' Hello World', (err) => {
if (err) {
throw err;
}
console.log('Updated!');
});
6. Database
A database is a crucial component of every application. To create an entire application, you must understand how to use it with Node.
In this section, we'll discuss the following databases:
1. MySQL
2. MongoDB
1. MySQL
A viral SQL database is MySQL. In this part, we will learn how to connect to it, query it, and use it with Node.js.
Millions of apps have used the widely used MySQL database. Along with Node, MySQL is also an option.
To utilize it with the MySQL database, we must install the module with the name MySQL. Before continuing, you must have the MySQL database installed on your PC.
Installing the node module to connect to MySQL is as follows:
Using this method, we may connect to the MySQL engine.
const mysql = require("mysql");
const pool = mysql.createPool({
connectionLimit: 100,
host: "localhost",
user: "root",
password: "",
database: "database_name",
debug: false,
});
pool.query("SELECT * from LIMIT 10", (err, rows) => {
if (err) {
console.log("error occurred during the connection.");
}
console.log(rows[0]);
});
Similar methods can run queries like INSERT, UPDATE, and DELETE.
Now, let's check MongoDB.
2. MongoDB
One of the popular NoSQL databases is MongoDB. Learn how to use Node.js to connect to it, run queries, and more.
Installing the MongoDB database on your PC is necessary before you can integrate it with Node.
Let's install the MongoDB driver for Node, assuming you already have MongoDB set up.
After requiring the module, we must establish a connection to the MongoDB instance.
This is the code.
const mongo = require("mongodb");
const url = "mongodb://localhost:27017/test";
mongo.connect(url, { useNewUrlParser: true }, (err, db) => {
if (err) {
console.log(err);
process.exit(0);
}
console.log("database connected!");
db.close();
});
Running on port 27017 is MongoDB. Any database that we want to work with can be connected.
We are establishing a connection to the test database in the code above.
We use the connect() method to connect to the database. Run the file after saving the code above in a file called "app.js":
You must create a collection before storing data in the MongoDB database.
Consider a collection as a SQL database table. Either the MongoDB shell or code can be used to construct a collection.
Let's try to update the MongoDB collection with some new data.
Data is kept in MongoDB in JSON format. JSON is a popular key-value-based data format utilized by many software layers.
Here is the code for how to accomplish it.
const mongo = require("mongodb");
const url = "mongodb://localhost:27017/";
mongo.connect(url, { useNewUrlParser: true }, (err, db) => {
if (err) {
console.log(err);
process.exit(0);
}
let data = { id: 100, name: "Shahid" };
var dbo = db.db("test");
console.log("database connected!");
dbo.collection("user").insert(data, (err, result) => {
if (err) {
console.log(err);
process.exit(0);
}
console.log("records added.");
console.log(result);
db.close();
});
});
Conclusion
This tutorial was about "learning Node.js from the beginning."
Node.js is a JavaScript runtime based on the Chrome V8 JavaScript engine. It makes it easy to make quick and scalable web applications.
You now know what Node.js is and why you should use it. You also know how to install Node.js and use its basic web server, express framework, node modules, file system, and database.
What are you waiting for? Let's start coding!
Contributor
Harikrishna
Harikrishna Kundariya, a marketer, developer, IoT, ChatBot & Blockchain savvy, designer, co-founder, Director of eSparkBiz Technologies, A Software Development Company.
Recommended Posts:-