Node Js Code Examples

Posted on  by admin

Node.js is a platform for building fast and scalable server applications using JavaScript. Node.js is the runtime and npm is the Package Manager for Node.js modules.

Visual Studio Code has support for the JavaScript and TypeScript languages out-of-the-box as well as Node.js debugging.

However, to run a Node.js application, you will need to install the Node.js runtime on your machine.

  • To get started in this walkthrough, install Node.js for your platform.
  • The Node Package Manager is included in the Node.js distribution.
  • You'll need to open a new terminal (command prompt) for the node and npm command-line tools to be on your PATH.
  • To test that you have Node.js installed correctly on your computer, open a new terminal and type node --version and you should see the current Node.js version installed.
  • Linux: There are specific Node.js packages available for the various flavors of Linux.
  • See Installing Node.js via package manager to find the Node.js package and installation instructions tailored to your version of Linux.
  • Windows Subsystem for Linux: If you are on Windows, WSL is a great way to do Node.js development.

You can run Linux distributions on Windows and install Node.js into the Linux environment. When coupled with the Remote - WSL extension, you get full VS Code editing and debugging support while running in the context of WSL.

Skipping hello world

To learn more, go to Developing in WSL or try the Working in WSL tutorial. Let's get started by creating the simplest Node.js application, "Hello World". Create an empty folder called "hello", navigate into and open VS Code:.

Tip: You can open files or folders directly from the command line. refers to the current folder, therefore VS Code will start and open the Hello folder.

Next steps

From the File Explorer toolbar, press the New File button:. and name the file app.js:. By using the .js file extension, VS Code interprets this file as JavaScript and will evaluate the contents with the JavaScript language service.

Refer to the VS Code JavaScript language topic to learn more about JavaScript support. Create a simple string variable in app.js and send the contents of the string to the console:.

Note that when you typed console.IntelliSense on the console object was automatically presented to you.

Great code editing

Also notice that VS Code knows that msg is a string based on the initialization to 'Hello World'. If you type msg. you'll see IntelliSense showing all of the string functions available on msg.

After experimenting with IntelliSense, revert any extra changes from the source code example above and save the file (⌘S (Windows, Linux Ctrl+S)).

Node.js Examples

It's simple to run app.js with Node.js. From a terminal, just type:. You should see "Hello World" output to the terminal and then Node.js returns. VS Code has an integrated terminal which you can use to run shell commands. You can run Node.js directly from there and avoid switching out of VS Code while running command-line tools.

View > Terminal (⌃` (Windows, Linux Ctrl+`) with the backtick character) will open the integrated terminal and you can run node app.js there:.

For this walkthrough, you can use either an external terminal or the VS Code integrated terminal for running the command-line tools.

  • As mentioned in the introduction, VS Code ships with a debugger for Node.js applications.
  • Let's try debugging our simple Hello World application.
  • To set a breakpoint in app.js, put the editor cursor on the first line and press F9 or click in the editor left gutter next to the line numbers.
  • A red circle will appear in the gutter.
  • To start debugging, select the Run View in the Activity Bar:.
  • You can now click Debug toolbar green arrow or press F5 to launch and debug "Hello World".
  • Your breakpoint will be hit and you can view and step through the simple application.

Notice that VS Code displays a different colored Status Bar to indicate it is in Debug mode and the DEBUG CONSOLE is displayed. Now that you've seen VS Code in action with "Hello World", the next section shows using VS Code with a full-stack Node.js web app.

Note: We're done with the "Hello World" example so navigate out of that folder before you create an Express app.

You can delete the "Hello" folder if you want as it is not required for the rest of the walkthrough.

Express is a very popular application framework for building and running Node.js applications.

You can scaffold (create) a new Express application using the Express Generator tool.

The Express Generator is shipped as an npm module and installed by using the npm command-line tool npm. Tip: To test that you've got npm correctly installed on your computer, type npm --help from a terminal and you should see the usage documentation.

Install the Express Generator by running the following from a terminal:. The -g switch installs the Express Generator globally on your machine so you can run it from anywhere.

We can now scaffold a new Express application called myExpressApp by running:. This creates a new folder called myExpressApp with the contents of your application.

The --view pug parameters tell the generator to use the pug template engine. To install all of the application's dependencies (again shipped as npm modules), go to the new folder and execute npm install:.

At this point, we should test that our application runs. The generated Express application has a package.json file which includes a start script to run node ./bin/www.

This will start the Node.js application running.

From a terminal in the Express application folder, run:. The Node.js web server will start and you can browse to http://localhost:3000 to see the running application.

Close the browser and from a terminal in the myExpressApp folder, stop the Node.js server by pressing CTRL+C. Now launch VS Code:. Note: If you've been using the VS Code integrated terminal to install the Express generator and scaffold the app, you can open the myExpressApp folder from your running VS Code instance with the File > Open Folder command.

An Express application

The Node.js and Express documentation does a great job explaining how to build rich applications using the platform and framework.

Visual Studio Code will make you more productive in developing these types of applications by providing great code editing and navigation experiences.

Debug your Express app

Open the file app.js and hover over the Node.js global object __dirname.

Notice how VS Code understands that __dirname is a string. Even more interesting, you can get full IntelliSense against the Node.js framework.

For example, you can require http and get full IntelliSense against the http class as you type in Visual Studio Code. VS Code uses TypeScript type declaration (typings) files (for example node.d.ts) to provide metadata to VS Code about the JavaScript based frameworks you are consuming in your application.

Type declaration files are written in TypeScript so they can express the data types of parameters and functions, allowing VS Code to provide a rich IntelliSense experience.

Thanks to a feature called Automatic Type Acquisition, you do not have to worry about downloading these type declaration files, VS Code will install them automatically for you.

You can also write code that references modules in other files.

For example, in app.js we require the ./routes/index module, which exports an Express.Router class. If you bring up IntelliSense on index, you can see the shape of the Router class.

You will need to create a debugger configuration file launch.json for your Express application.

Click on the Run icon in the Activity Bar and then the Configure gear icon at the top of the Run view to create a default launch.json file.

Select the Node.js environment by ensuring that the type property in configurations is set to "node".

When the file is first created, VS Code will look in package.json for a start script and will use that value as the program (which in this case is "${workspaceFolder}\\bin\\www) for the Launch Program configuration.

Save the new file and make sure Launch Program is selected in the configuration dropdown at the top of the Run view. Open app.js and set a breakpoint near the top of the file where the Express app object is created by clicking in the gutter to the left of the line number.

Press F5 to start debugging the application.

VS Code will start the server in a new terminal and hit the breakpoint we set. From there you can inspect variables, create watches, and step through your code.

If you'd like to learn how to deploy your web application, check out the Deploying Applications to Azure tutorials where we show how to run your website in Azure.

There is much more to explore with Visual Studio Code, please try the following topics:. Settings - Learn how to customize VS Code for how you like to work.

Hello World

Debugging - This is where VS Code really shines. Video: Getting started with Node.js debugging - Learn how to attach to a running Node.js process.

  • Node.js debugging - Learn more about VS Code's built-in Node.js debugging.
  • Debugging recipes - Examples for scenarios like client-side and container debugging.

  • Tasks - Running tasks with Gulp, Grunt and Jake.
  • Showing Errors and Warnings. What is Node.js? Right here if we go to their website, we can see that it says Node.js is a javascript runtime environment built on Chrome’s V8 Javascript engine.

  • So Node.js is this program that we installed in our server, a computer, Right that uses this program right here called Chrome’s V8 Javascript engine and this program is built on C++.
  • So what Node.js is actually doing is using this program that Chrome or Google created that uses the language C++ to do other things that Javascript can not normally do.

    Hope you guys like these tutorials, feel free to drop any comments in the comment section below.

  • Node.js Examples : We shall go through examples of basics, fs module, mysql module, http module, url module, parsing json, etc.

Following is the list of Node.js Examples. Following is a simple Node.js Example to print a message to console.

  1. Following is Node.js Example where we create a Calculator Node.js Module with functions add, subtract and multiply.
  2. And use the Calculator module in another Node.js file.

  3. Following Node.js Example creates a file with data provided.
  4. Run the program using node command in terminal or command prompt :. The file should be created next to your example node.js program with the content ‘Learn Node FS module’.

  5. Run the program using node command in terminal or command prompt :.
  6. make sure there is a file named ‘sample.txt’ next to the node.js example program.

    Run the program using node command in terminal or command prompt :.

  7. The file is successfully deleted. In this example, we shall write content, “Hello !” , to a text file sample.txt.

When the above program is run in Terminal,. We shall apply a filter based on marks and fetch only those records with marks greater than 90.

Open a terminal from the location of above .js file and run selectFromWhere.js Node.js MySQL example program.

An example to sort entries in ascending order w.r.t a column.

Run the above Node.js MySQL ORDER BY example program.

The records are sorted in ascending order with respect to marks column.

Run above Node.js MySQL program in Terminal.

Run the above program in Terminal. Execute DELETE FROM query on specified table with filter applied on one or many properties of records in the table.

We can access the records in Result Set as an array and properties of a record using DOT (.) Operator.

Deploy your application

Run the above program using node in Terminal. Following example helps you to use JSON.parse() function and access the elements from JSON Object. Node.js Example – A HTTP Web Server that prepares a response with HTTP header and a message.

Open a browser and hit the url, “http://127.0.0.1:9000/”, to trigger a request to our Web Server. First things first: you need to realize that Node is intended to be used for running standalone javascript programs. This isn’t a file referenced by a piece of HTML and running in a browser. It’s a file sitting on a file system, executed by the Node program, running as what amounts to a daemon, listening on a particular port.

The classic example here is “Hello World,” detailed on the Node website.

Almost everyone starts with Hello World, though, so check that out on your own, and skip straight to something a lot more interesting: a server that can send static files, not just a single line of text:.

Thanks much to Mike Amundsen for the pointer to similar code.

This particular example was posted by Devon Govett on the Nettuts+ training blog, although it’s been updated for the current version of Node in a number of places.

Devon’s entire tutorial post is actually a great companion piece on getting up to speed on Node once you have a handle on the basics.

If you would like to become a Node.js Certified professional, then visit Mindmajix - A Global online training platform: "Node.js Training and Certification Course".

This course will help you to achieve excellence in this domain. If you’re new to Node, type this code into a text file and save the file as NodeFileServer.js.

Then head out to the Node website and download Node or check it out from the git repository.

You’ll need to build the code from source; if you’re new to Unix, make, and configure, then check out the online build instructions for help.

Don’t worry that you’ve put aside NodeFileServer.js for a moment; you’ll come back to it and more JavaScript shortly.

For now, soak in the realization that you’ve just run through the classic Unix configuration and build process:. That should come with another realization: Node itself isn’t JavaScript. Node is a program for running JavaScript but isn’t JavaScript itself. In fact, Node is a C program. Do a directory listing on the Node/src directory and you’ll see something like this:. For all of you who think that JavaScript is a poor language in which to be writing server-side tools, you’re half right.

Yes, JavaScript is not equipped to deal with operating system-level sockets and network connectivity.

But Node isn’t written in JavaScript; it’s written in C, a language perfectly capable of doing the grunt work and heavy lifting required for networking.

JavaScript is perfectly capable of sending instructions to a C program that can be carried out in the dungeons of your OS. In fact, JavaScript is far more accessible than C to most programmers — something worth noting now, and that will come up again and again in the reasons for looking seriously at Node. The primary usage of the Node further reflects that while Node works with JavaScript, it isn’t itself JavaScript. You run it from the command line:. And there you have it.

Heck, a big appeal to Node is that you can actually write a server without worrying about C.

That’s the point.

Make sure you still have your NodeFileServer.js code running via Node.

Then you can hit your local machine — on port 1337 — and see this unremarkable output.

Yes, this is about as mundane as you can get. Well, that is, until you realize that you’ve actually written a file server in about 20 lines of code. The output you see — the actual code of the script you wrote — isn’t canned in the script itself. It’s being served from the file system. Throw an image into the same directory, and simply add the name of the image to the end of your URL, like https://localhost:8080/my_image.png:. Node happily serves this binary image up. That’s pretty remarkable when you again refer to the brevity of the code. On top of that, how hard would it be if you wanted to write your own server code in JavaScript?

Not only that, but suppose you wanted to write that code to handle multiple requests? (That’s a hint; open up four, five, or 10 browsers and hit the server.) The beauty of Node is that you can write entirely simple and mundane JavaScript to get these results.

A NodeJS module helps you read large text files, line by line, without buffering the files into memory.Installation:.

There’s a lot more to talk about around Node than in the actual code that runs a server.

Still, it’s worth taking a blisteringly fast cruise through NodeFileServer.js before moving on.

Node runs JavaScript but isn’t JavaScript

Take another look at the code: First, you have a call to a function called require().

The use of require() has been a long-standing request by programmers.

You can actually find this mentioned in some of the discussions on JavaScript modularity, as well as germane to CommonJS, and a pretty cool implementation by O’Reilly author David Flanagan from 2009.

In other words, require() may be new to you, but it isn’t an untested, careless piece of Node code. It’s core to using modular JavaScript and something of which Node takes a heavy advantage.

Then, the resulting HTTP variable is used to create a server.

That server is handed a function block to run when it’s contacted.

This particular function ignores the request completely and just writes out a response, in text/plain, saying simply “Hello World”.

Pretty straightforward stuff.In fact, this lays out the standard pattern for Node usage:.

Define the type of interaction and get a variable for working with that interaction (via require()).2.

Create a new server (via createServer()).3. Hand that serves a function for handling requests.

The request handling function should include a request …… and a response.4.

Tell the server to start handling requests on a specific port and IP (via listen).

Explore Node.js Sample Resumes!

Download & Edit, Get Noticed by Top Employers!

For example, consider this code which can act as a node module.

const calc =(a,b,p)=>{
if(a || b || p ){
return"Please provide all parameters";
}
switch(p){
case'+':{
return a+b;
break;
}
case'-':{
return a-b;
break;
}
case'*':{
return a*b;
break;
}
case'/':{
return a/b;
break;
}
default:{return;}
}
}
exports.calc=calc;//very important line

You can reuse this module in your code like this:

var dt = require('./mymodule');
console.log(dt.calc(10,20,'+'));

This is a really simple example. However, this gives an idea about how to create node modules. If you are interested in more detailed information, visit this tutorial.

Node modules are managed by the file called package.json. This file contains the list of the packages your project is using along with the version number etc.

A typical package.json file looks like this:

{
"name":"codeforgeek-app-server",
"version":"1.0.0",
"description":"",
"main":"app.js",
"scripts":{
"start":"node app.js"
},
"keywords":[],
"author":"",
"license":"ISC",
"dependencies":{
"async":"^3.1.0",
"axios":"^0.19.0",
"bcrypt":"^4.0.1",
"chalk":"^2.4.2",
"connect-redis":"^4.0.4",
"cors":"^2.8.5",
"express":"^4.17.1",
"mongodb":"^3.2.7",
"nconf":"^0.10.0",
"nodemailer":"^6.3.0",
"pug":"^2.0.4",
"reading-time":"^1.2.0",
"redis":"^2.8.0",
"winston":"^3.2.1"
}
}

We also specify details such as project name, version, entry file of the project in the package.json.

All the dependencies that are installed using npm install command are listed in the package.json. You should always maintain the updated version of package.json while dealing with the packages.

Let’s jump to the next step.

Node.js Example – Parse JSON File

The fs module provides an API for interacting with the file system of your operating system. To use this module, require it in your code like this:

There are lots of methods provided under this node module to perform various tasks such as creating files, writing data into a file, reading data from files, etc.

You can use fs.readFile() or fs.readFileSync() method to read files in Node.

For example: 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());
});

Using the readFileSync() method.

const fs = require('fs');
const data = fs.readFileSync('./lorem.txt'); console.log(data.toString());

The simplest approach to check whether the file exists or not is by using the readFile() function.

However, this function does open the file descriptor and occupies some memory too.

If you just want to check the file existences in the system, I highly recommend the access() function. Here is the code:

const fs = require('fs');
const path ='./config.js';
fs.access(path, fs.F_OK,(err)=>{
if(err){
console.error(err);
return;
}
});

The file system module provides three methods to create files:

  1. fs.open()
  2. fs.writeFile()
  3. fs.appendFile()

fs.open() method opens a new file or creates a new empty file if it does not exist in the specified path.

It takes the second parameter which acts as a flag such as w for writing, 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!');
});

fs.writeFile() method allows you to create or replace files with the content.

If a file exists, it will replace the content with the provided content and if the file does not exist, it will create it.

const fs = require('fs');
fs.writeFile('file.txt','Hello Word!',(err)=>{
if(err){
throw err;
}
console.log('Saved!');
});

fs.appendFile() method appends the provided content at the end of the file.

const fs = require('fs');
fs.appendFile('file.txt',' Hello World',(err)=>{
if(err){
throw err;
}
console.log('Updated!');
});

To delete a file, we can use fs.unlink() method.

const fs = require('fs');
fs.unlink('file.txt',(err)=>{
if(err){
throw err;
}
console.log('File deleted!');
});

To rename a file, we can use the fs.rename() method.

const fs = require('fs');
fs.rename('newfile.txt','oldfile.txt',(err)=>{
if(err){
throw err;
}
console.log('File Renamed!');
});

You can also copy files using the fs.copy() method.

const fs = require('fs');
fs.copyFile(file.txt', 'copyfile.txt', (err) => {
if (err) {
throw err;
}
console.log('File is copied!');
});

Let’s jump to the next step.

Node.js Example – UPDATE Table Entries

Express is a popular framework to develop web applications in Node.

Express is widely used and can be used to develop web applications such as Web Server, REST API Server, Streaming engine, etc.

In this section, we are going to learn about express and we will create a simple web server with different routes.

Terminologies we will use in this section are:

  1. route: This means an endpoint. for example facebook.com/profile so the profile is a route.
  2. middleware: A set of functions that will be executed in the chosen order.

Let’s begin.

Create a new folder and switch to it using a terminal or command prompt.

Create a new node project using the following command.

This will create a sample package.json for your project. To install the express module, run the following command.

The latest version of the express framework will be installed in your project. Now create a new file and name it app.js. In this file, we will write our web server using express.

const express = require('express');
const app = express();
app.listen(process.env.port||3000);
console.log('Web Server is listening at port '+(process.env.port||3000));

In the code shown above, we have required the express module and created a new instance of it.

In the end, we have started our Server using the listen() function.

Routers are simply an endpoint of a server.

For example, facebook.com/codeforgeek, here the codeforgeek is a route.

We need to create routers in our web application to serve different requests. We will create the following routes in our web application.

  1. home
  2. profile
  3. login
  4. logout

Express routers allow us to serve different HTTP methods such as GET, POST, PUT, DELETE, HEAD. Here is how to create a router.

const express = require('express');
const app = express();
const router = express.Router();
router.get('/home',(req,res)=>{
res.send('Hello World, This is home router');
});
router.get('/profile',(req,res)=>{
res.send('
Hello World, This is profile router
');
});
router.get('/login',(req,res)=>{
res.send('
Hello World, This is login router
');
});
router.get('/logout',(req,res)=>{
res.send('
Hello World, This is logout router
');
});
app.use('/', router);
app.listen(process.env.port||3000);
console.log('Web Server is listening at port '+(process.env.port||3000));

Let’s run our application, save the file, and run the code using the following command.

You should see the following message in the terminal.

Open your browser and visit the routes.

Here is the profile page.

You can also send HTML/JSON/XML as a response.

Express provides middleware function support. Middleware functions as the name suggests can be used to make changes in the request/response lifecycle of the express. There are five types of middleware functions in the express.

  • Application middleware
  • Router middleware
  • Error-handling middleware
  • Built-in middleware
  • Third-party middleware

Debugging Hello World

We can use middleware in the application object of the express. For example:

const express = require('express');
const app = express();
app.use((req, res, next)=>{
console.log('Time:',Date.now());
next();
});
app.listen(process.env.port||3000);
console.log('Web Server is listening at port '+(process.env.port||3000));

NodeJS Example – ORDER entries BY a column

In a similar way as application middleware, we can use router middleware. For example:

const express = require('express');
const app = express();
const router = express.Router();
router.use((req, res, next)=>{
console.log('Time:',Date.now());
next();
});
router.get('/home',(req,res)=>{
res.send("ok")
});
app.use('/', router);
app.listen(process.env.port||3000);
console.log('Web Server is listening at port '+(process.env.port||3000));

Node.js Example 1 – Simple Node.js Example

We can use this middleware to catch errors.

app.use((err, req, res, next)=>{
res.status(500).send('Something broke!')
});

Learn more about this function here.

Integrated Terminal

Express provides some middleware by default such as static, JSON, etc.

Node.js Example – Delete a File

We can use third-party middlewares such as body-parser. Here is how we can install third-party middleware.

To use this middleware, we need to require our code and load it.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
router.get('/home',(req,res)=>{
res.send('
Hello World, This is home router
');
});
router.get('/profile',(req,res)=>{
res.send('
Hello World, This is profile router
');
});
router.get('/login',(req,res)=>{
res.send('
Hello World, This is login router
');
});
router.get('/logout',(req,res)=>{
res.send('
Hello World, This is logout router
');
});
// add middleware before routes
app.use(bodyParser.json());
app.use('/', router);
app.listen(process.env.port||3000);
console.log('Web Server is listening at port '+(process.env.port||3000));

If you are interested in creating your middleware, I recommend you this article.

We can handle sessions in Express using express-session middleware. We can use this middleware to create, track, and delete sessions.

To use this module in our code, load this as a middleware.

Now, we can use req.session object to create, track, and delete sessions.

To learn more about the session, please read this article.

We can also use external stores such as Redis to store session values instead of storing them in memory.

Let’s jump to the next step and learn about the integration of databases with Node.

Node.js Example – Create a Module

The database is an integral part of any application. You must know how to use it with Node to build a complete application.

We are going to cover the following databases in this section:

  • MySQL
  • MongoDB
  • PostgreSQL
  • Redis

Let’s begin with MySQL.

NodeJS Example – INSERT entries INTO Table

MySQL is a very popular SQL database. In this section, we will learn how to connect, query, and use it with NodeJS.

MySQL is a very popular database and has been used in millions of applications. We can use MySQL with Node as well.

We need to install the module name as MySQL to use it with the MySQL database.

You need to have the MySQL database installed in your system before proceeding.

To install the node module to connect with MySQL:

Here is how we can establish a connection 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]);
});

You can execute the queries such as INSERT, UPDATE and DELETE in a similar fashion. Learn more in detail about using Node and MySQL.

Let’s learn about MongoDB.

Latest Node.js Tutorial Series & Examples

MongoDB is a very popular NoSQL database. Learn how to connect, query, and use it with NodeJS.

MongoDB is one of the most popular general-purpose NoSQL database engines.

To integrate MongoDB with Node, you need to install the MongoDB database in your system.

Click here to visit the official site and download the latest version of MongoDB.

Assuming you have MongoDB installed, let’s install the MongoDB driver for Node.

We need to require the module and then connect to the MongoDB instance. Here 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();
});

MongoDB runs on port 27017. We can connect to any database we like to work with.

In the code shown above, we are connecting to the test database.

We are using the connect() method to establish a connection with the database. Save the code above in a file called ‘app.js’ and run the file:

You should see output similar to this:

In order to store data in the MongoDB database you need to create a collection.

Think of collection as a table in the SQL database. You can either create a collection in the MongoDB shell or you can do it in code. Here is how you can do it in code.

const mongo = require("mongodb");
const url ="mongodb://localhost:27017/";
mongo.connect(url,{ useNewUrlParser:true},(err, db)=>{
if(err){
console.log(err);
process.exit(0);
}
console.log("database connected!");
var dbo = db.db("test");
dbo.createCollection("customers",(err, result)=>{
if(err){
console.log(err);
process.exit(0);
}
console.log("collection created!");
db.close();
});
});

Let’s try to add some data in the MongoDB collection.

MongoDB stores data in a JSON format. JSON is a key-value based data format widely used across various layers of software.

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();
});
});

You can also search for the data inside the collection using the findOne() function.

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").findOne({},(err, result)=>{
if(err){
console.log(err);
process.exit(0);
}
console.log("Here is the record");
console.log(result);
db.close();
});
});

After running the code above, you should see a record similar to this.

You can also perform tons of other operations such as query(), sort(), delete() etc. Learn more about MongoDB here.

Let’s proceed towards the next database, PostgreSQL.

Node.js Example – Read a File

PostgreSQL is a very popular SQL database. Learn how to connect, query, and use it with NodeJS.

PostgreSQL, also referred to as Postgres, is a free and popular relational database system.

Postgres competes with relational databases like MySQL, SQL Server, or MariaDB.

You need to have Postgres installed in your system to continue with this tutorial. Visit the official download page to install Postgres to grab a copy and install Postgre in your system.

We need to create a user credential in Postgres in order to connect to the database. Connect to Postgres using the default credentials. Run this command in your terminal.

Create a new user.

CREATEROLE codeforgeek WITH LOGIN PASSWORD 'somepassword'

Give permission to the new user.

Now, exit from the current session and login again with your new user credentials.

Create a new database.

Switch to a new database.

Create a new table.

users=>CREATETABLE profile (
ID SERIAL PRIMARYKEY,
name VARCHAR(30),
email VARCHAR(30)
);

Insert some records.

INSERT
INTO profile (name, email)
VALUES
('Jerry','[email protected]'),
('George','[email protected]');

Let’s connect to it using our Node program. Install the dependency.

Create an app.js file and add the following code in it.

const Pool = require("pg").Pool;
const pool =new Pool({
user:"codeforgeek",
host:"localhost",
database:"users",
password:"somepassword",
port:5432,
});
// read information from table
pool.query("SELECT * FROM profile ORDER BY id ASC",(error, results)=>{
if(error){
console.log(error);
return;
}
console.log(results);
});
// add a new user profile.
const name ="Shahid";
const email ="[email protected]";
pool.query(
"INSERT INTO profile (name, email) VALUES ($1, $2)",
[name, email],
(error, results)=>{
if(error){
console.log(error);
return;
}
console.log(results);
}
);

We created a new Pool connection to Postgres. We first executed a SELECT query using the pool.query() method. The pool connection automatically returns the connection to the pool after executing the query.

Let’s proceed towards the final database in the section.

Node.js Example – Write to a File

Redis is the high-performance in-memory database used as a data structure store. Redis supports hash, strings, lists, and other complicated data structures by maintaining very high performance.

Redis along with Node.js can be used to solve various problems such as cache server or message broker.

You can install Redis in your system by following the official installation guides.

Once installed, you can run the Redis server using the following command.

You should see the following in your terminal.

To access the Redis command-line interface, run the following command from a separate terminal.

To configure Redis with Node, we need to install the Redis driver.

Here is the sample code to connect to the Redis server.

var redis = require('redis');
var redisClient = redis.createClient({host :'localhost', port :6379});
redisClient.on('ready',function(){
console.log("Redis is ready");
});
redisClient.on('error',function(){
console.log("Error in Redis");
});

When you run this command, you should have a connection with the Redis.

You can use set(), get() and other Redis commands to perform various operations.

To dig deeper into Redis, you can visit this tutorial.

NodeJS Example – SELECT from Table with WHERE clause

Let’s learn how to deploy our Node application. I deploy all my projects on DigitalOcean. I highly recommend it to developers. If you have never tried DigitalOcean, give it a shot with a $10 discount for the first month.

Click here to go to the DigitalOcean droplet creation screen.

Choose a $5 plan and create the droplet. After creating a droplet wait for some time, DigitalOcean will send you an email containing the credentials. Login to your droplet using the following command.

Provide the password given in the email and you are good to go.

Once you are logged in, update the system using the following command.

Install Git.

Install the latest Node on your Server.

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

sudo apt-get install -y nodejs

Install the PM2 process manager.

Our server is ready to host our Node applications.

Github is a code hosting platform. Learn how to host your code in the Github platform.

Let’s push our code to Github. Go to Github.com and create a new repository.

Copy the repository path. Assuming you have Git installed in your machine. Switch to the project directory and execute these commands one by one.

git init
git add .
git commit - m "first push"
git remote add origin << github repo URL >>
git push origin master

Login to your server using SSH.

Clone the Github project.

Switch to the project directory.

Install dependencies.

Run the Node project using PM2.

PM2 is a process management tool for Node. Using PM2 we can ensure 99% uptime of your application.

Test your application using Droplet IP and port on which your application is running.

Awesome. You have successfully developed and deployed your application. Here is another article related to deployment of application in the production server.

NodeJS Example – SELECT FROM Table

I have created a PDF format of this Node js tutorial for beginners. You can visit this page to download the book.

Running Hello World

We have written a lot of Node js tutorials on different topics, listing some of the best articles for you to read it further.

Building Email Verification System Using Node and Redis
Microservices Architecture with Node.js
Load Balancing Node.js Application Servers with Nginx
Building a URL Shortener with Node.Js and Redis
Load Balancing Node.js Application Servers with Nginx