{"id":6897,"date":"2021-04-12T21:25:12","date_gmt":"2021-04-12T15:55:12","guid":{"rendered":"https:\/\/codeforgeek.com\/?p=6897"},"modified":"2023-12-22T19:04:38","modified_gmt":"2023-12-22T13:34:38","slug":"node-js-tutorial-step-by-step","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/node-js-tutorial-step-by-step\/","title":{"rendered":"Node.js Tutorial for Beginners Step by Step With Examples"},"content":{"rendered":"<p>This Node js tutorial is designed for beginners to help you learn Node.js step by step. All you need to do is follow this Node.js tutorial stepwise. Each step covers important topics related to Node.js.<\/p>\n<p>This Node.js tutorial is divided into 7 steps. We expect you to follow this step by step.<\/p>\n<p>We are going to cover the following topics in this Node.js tutorial:<\/p>\n<ul>\n<li>Step 1: Node js basic concepts &#8211; Libuv, Event loop, Libev.<\/li>\n<li>Step 2: Building a Simple Web Server in Node.js.<\/li>\n<li>Step 3: Node.js modules and NPM.<\/li>\n<li>Step 4: File system module.<\/li>\n<li>Step 5: Express framework.<\/li>\n<li>Step 6: Databases &#8211; MySQL, MongoDB, PostgreSQL and Redis.<\/li>\n<li>Step 7: Deployment &#8211; deploying applications in Digitalocean Server.<\/li>\n<\/ul>\n<p>After reading this Node.js tutorial, you should be able to build applications using Node.js and deploy it on a cloud server. Let&#8217;s begin.<\/p>\n<h2>Step 1: Node js basic concepts<\/h2>\n<p>Node.js runs on top of V8\u2014Chrome runtime engine\u2014that compiles the JavaScript code in the native machine code (one of the reasons why Google Chrome runs fast and consumes a lot of memory), followed by the custom C++ code. <\/p>\n<p>The original version has 8,000 lines of code (LOC)\u2014and then, the standard libraries for programmers. The following is the figure of Node.js architecture: <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2017\/08\/Nodejs-Architecture.png\" alt=\"Nodejs Architecture\" width=\"678\" height=\"490\" class=\"alignnone size-full wp-image-4102\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2017\/08\/Nodejs-Architecture.png 678w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2017\/08\/Nodejs-Architecture-300x217.png 300w\" sizes=\"(max-width: 678px) 100vw, 678px\" \/><\/p>\n<h3>V8<\/h3>\n<p>The V8 JavaScript engine is an open-source JavaScript engine developed for the Chrome project. The innovation behind V8 is that it compiles the JavaScript code in native machine code and executes it. <\/p>\n<p>The developers of V8 used the just-in-time (JIT) compiler methodology to improve the code compilation time. It is open-source and is used in the Node.js and MongoDB project.<\/p>\n<p>Link: <a href=\"https:\/\/github.com\/v8\/v8\" rel=\"noopener noreferrer\" target=\"_blank\">https:\/\/github.com\/v8\/v8<\/a><\/p>\n<h3>Event driven I\/O \u2013 libuv<\/h3>\n<p>The libuv library is a cross-platform library that provides an asynchronous I\/O facility by enabling an event-driven I\/O operation. The libuv library creates a thread for the I\/O operation (file, DNS, HTTP, and so on) and returns a callback. <\/p>\n<p>Upon completion of the particular I\/O operation, it returns the events so that the callee program does not have to wait for the completion of the I\/O operation. <\/p>\n<h3>Working of libuv \u2013 the core of Node.js<\/h3>\n<p>As I mentioned earlier, libuv assigns threads for the I\/O operation and returns the callback to the callee program. Therefore, Node.js internally creates threads for I\/O operation; however, it gives the programmer access to a single runtime thread. In this way, things are simple and sweet:  <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.07.50-AM.png\" alt=\"how libuv works\" width=\"843\" height=\"541\" class=\"alignnone size-full wp-image-6130\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.07.50-AM.png 843w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.07.50-AM-300x193.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.07.50-AM-768x493.png 768w\" sizes=\"(max-width: 843px) 100vw, 843px\" \/><\/p>\n<p>When you make an HTTP request to the web server built using Node. It creates the libuv thread and is ready to accept another request. <\/p>\n<p>As soon as the events are triggered by libuv, it returns the response to the user. The libuv library provides the following important core features:<\/p>\n<ul>\n<li>Fully featured event loop<\/li>\n<li>Asynchronous filesystem operations<\/li>\n<li>Thread pool<\/li>\n<li>Thread and synchronization primitives<\/li>\n<li>Asynchronous TCP and UDP sockets<\/li>\n<li>Child process<\/li>\n<li>Signal handling<\/li>\n<\/ul>\n<p>The libuv library internally uses another famous library called <strong>libeio<\/strong>, which is designed for <strong>threading<\/strong> and <strong>asynchronous I\/O<\/strong> events and libev, which is a high-performance event loop. <\/p>\n<p>Therefore, you can treat libuv as a package wrapper for both of them. <\/p>\n<p>Let\u2019s learn a little bit about multi-threading and single threading.<\/p>\n<p>The multi-threading approach provides parallelism using threads so that multiple programs can simultaneously run. <\/p>\n<p>it is really difficult to handle concurrency and deadlock in a multi-threading system. <\/p>\n<p>On the other hand, with single-threading, there is no chance of deadlock in the process, and managing the code is also easy. You can still hack and busy the event loop for no reason; however, that&#8217;s not the point. <\/p>\n<p>Consider the following working diagram that is developed by StrongLoop\u2014one of the core maintainers of Node.js: <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.13.53-AM.png\" alt=\"Multithreading systems\" width=\"815\" height=\"490\" class=\"alignnone size-full wp-image-6134\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.13.53-AM.png 815w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.13.53-AM-300x180.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.13.53-AM-768x462.png 768w\" sizes=\"(max-width: 815px) 100vw, 815px\" \/><\/p>\n<p>Node.js uses single-threading for runtime environment; however, internally, it does create multiple threads for various I\/O operations. <\/p>\n<p>It doesn&#8217;t imply that it creates threads for each connection, libuv contains the Portable Operating System Interface (POSIX) system calls for some I\/O operations. <\/p>\n<p>Multi-threading blocks the I\/O until the particular thread completes its operation and results in overall slower performance.<\/p>\n<p>Consider the following image: <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.14.44-AM.png\" alt=\"Single threading system\" width=\"763\" height=\"435\" class=\"alignnone size-full wp-image-6135\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.14.44-AM.png 763w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.14.44-AM-300x171.png 300w\" sizes=\"(max-width: 763px) 100vw, 763px\" \/><\/p>\n<p>If the single-threading programs work correctly, they will never block the I\/O and will be always ready to accept new connections and process them.<\/p>\n<p>As you can see in the image earlier, I\/O does not get blocked by any thread in Node.js. Then, how does it notify particular processes that the task has been done or an error has occurred? <\/p>\n<h3>Importance of event loop<\/h3>\n<p>Node.js is <strong>asynchronous<\/strong> in nature and you need to program it in an asynchronous way, which you cannot do unless you have a clear understanding of the event loop. <\/p>\n<p>If you know how the event loop works, you will no longer get confused and hopefully, never block the event loop.<\/p>\n<h3>How Event Loop Works<\/h3>\n<p>The Node.js runtime system has an execution <strong>stack<\/strong>, where it pushes every task to execute. <\/p>\n<p>The operating system pops the task from the execution stack and conducts the necessary action required to run the task. <\/p>\n<p>To run the <strong>asynchronous<\/strong> code, this approach won&#8217;t work. The libuv library introduces a queue that stores the callback for each asynchronous operation. <\/p>\n<p>Event loop runs on a specific interval, which is called <strong>tick<\/strong> in the Node.js terminology and checks the stack. <\/p>\n<p>If the stack is empty, it takes the callback from the queue and pushes it in the stack for execution, as shown in the following figure: <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.18.31-AM.png\" alt=\"How event loop works\" width=\"642\" height=\"387\" class=\"alignnone size-full wp-image-6137\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.18.31-AM.png 642w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.18.31-AM-300x181.png 300w\" sizes=\"(max-width: 642px) 100vw, 642px\" \/><\/p>\n<p>The libuv library creates the thread and returns the callback to us. <\/p>\n<p>As it&#8217;s an asynchronous operation, it goes to the queue instead of the stack and the event loop fetches it when the stack is empty and does the execution. You can validate the same concept using the setTimeout() function.<\/p>\n<p>Consider the following code:<br \/>\n<code lang='javascript'><br \/>\nconsole.log('i am first');<\/p>\n<p>setTimeout(timeout() => {<br \/>\n  console.log('i am second');<br \/>\n}, 5000); <\/p>\n<p>console.log('i am third');<br \/>\n<\/code><\/p>\n<p>If you run this code, you will get an output similar to the following:<br \/>\n<code><br \/>\ni am first<br \/>\ni am third<br \/>\ni am second<br \/>\n<\/code><\/p>\n<p>The reason is obvious, <strong>setTimeout()<\/strong> waits for five seconds and prints its output; however, that does not block the event loop. Let&#8217;s set the timer to 0 seconds and see what happens: <\/p>\n<p><code lang='javascript'><br \/>\nconsole.log('i am first');<\/p>\n<p>setTimeout(timeout() => {<br \/>\n  console.log('i am second');<br \/>\n}, 0);<\/p>\n<p>console.log('i am third');<br \/>\n<\/code><\/p>\n<p>The output is still the same:<br \/>\n<code><br \/>\ni am first<br \/>\ni am third<br \/>\ni am second<br \/>\n<\/code><\/p>\n<p>Why so? Even if you set the timer to 0, it goes in the queue; however, it is immediately processed as its time is 0 second. <\/p>\n<p>The event loop recognizes that the stack is still not empty, that is, the third console was in process; therefore, it pushes the callback after the next tick of the event loop.<\/p>\n<p>We have covered the basics of Node. Let&#8217;s proceed ahead with the installation in your operating system. If you already have Node installed, kindly skip this section.<\/p>\n<h3>Installing Node in Your Operating System<\/h3>\n<p>To install Node in Windows Operating System, follow these steps:<\/p>\n<ul>\n<li>Step 1: Download the Installer<\/li>\n<p>Download the Node installer from the official site. <\/p>\n<li>Step 2: Run the installer. <\/li>\n<p>Run the installer and click Next until the setup wizard is complete. <\/p>\n<li>Step 3: Verify the installation<\/li>\n<p>Open command prompt or PowerShell and run the following command.<br \/>\n<code>node -v<\/code><br \/>\nIt should return the node version. <\/p>\n<li>Step 4: Update the NPM<\/li>\n<p><code>npm install -g npm<\/code>\n<\/ul>\n<p>To install Node in the Mac operating system, follow these steps:<\/p>\n<ol>\n<li>Step 1: Download the Installer<\/li>\n<p>Download the Node installer from the official site. <\/p>\n<li>Step 2: Run the installer<\/li>\n<p>Run the installer and click Continue until the setup wizard is complete.<br \/>\n<img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/mac-node-setup.png\" alt=\"mac node setup\" width=\"733\" height=\"550\" class=\"alignnone size-full wp-image-6238\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/mac-node-setup.png 733w, https:\/\/codeforgeek.com\/wp-content\/uploads\/mac-node-setup-300x225.png 300w\" sizes=\"(max-width: 733px) 100vw, 733px\" \/><\/p>\n<li>Step 3: Verify the installation<\/li>\n<p>Open the terminal and run the following command.<br \/>\n<code>node -v<\/code><br \/>\nIt should return the node version.<\/p>\n<li>Step 4: Update the NPM using the following command.<\/li>\n<p><code>npm install -g npm<\/code>\n<\/ol>\n<p>To install Node in the Ubuntu operating system, open the terminal and run the following command one by one. <\/p>\n<p><code>curl -sL https:\/\/deb.nodesource.com\/setup_12.x | sudo -E bash - <\/code><\/p>\n<p>Then,<br \/>\n<code>sudo apt-get install -y nodejs<\/code><\/p>\n<p>Also, install the build tools.<br \/>\n<code>sudo apt-get install -y build-essential<\/code><\/p>\n<p>Update the NPM.<br \/>\n<code>sudo npm install -g npm<\/code><\/p>\n<p>Verify the installation, run the following command.<br \/>\n<code>node -v<\/code><\/p>\n<p>It should return the version of Node installed in your system. In our case, it is V12.<\/p>\n<p>Alright, let&#8217;s move to the next step.<\/p>\n<h2>Step 2: Building a Simple Web Server in Node.js<\/h2>\n<p>Let&#8217;s build a simple Web application that returns a message as &#8220;Hello World&#8221; when user request the server. We will use the native <strong>HTTP<\/strong> module of Node to achieve the Web Server functionality. Here is the code: <\/p>\n<p><code lang='javascript'><br \/>\nconst http = require('http');<br \/>\nconst hostname = 'localhost';<br \/>\nconst port = 3000;<br \/>\nconst server = http.createServer((req, res) => {<br \/>\n  res.statusCode = 200;<br \/>\n  res.setHeader('Content-Type', 'text\/plain');<br \/>\n  res.end('Hello World ');<br \/>\n}); <\/p>\n<p>server.listen(port, hostname, () => {<br \/>\n  console.log(`Server running at   http:\/\/${hostname}:${port}\/`);<br \/>\n});<br \/>\n<\/code><\/p>\n<p>Copy\/paste it in a new file. Name the file as hello.js and save it. <\/p>\n<p>To run this code, open your terminal and switch to the location where you have stored the file. Run this command to execute your code. <\/p>\n<p><code><br \/>\nnode hello.js<br \/>\n<\/code><\/p>\n<p>You should have the following message on the terminal. <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.27.13-AM.png\" alt=\"Node hello world\" width=\"1175\" height=\"459\" class=\"alignnone size-full wp-image-6140\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.27.13-AM.png 1175w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.27.13-AM-300x117.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.27.13-AM-768x300.png 768w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.27.13-AM-1024x400.png 1024w\" sizes=\"(max-width: 1175px) 100vw, 1175px\" \/><\/p>\n<p>Open your browser and type localhost:3000 and hit enter. You should see the following message. <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.28.43-AM.png\" alt=\"Node Hello World\" width=\"774\" height=\"487\" class=\"alignnone size-full wp-image-6141\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.28.43-AM.png 774w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.28.43-AM-300x189.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2019-05-23-at-4.28.43-AM-768x483.png 768w\" sizes=\"(max-width: 774px) 100vw, 774px\" \/><\/p>\n<p>Congratulations!<\/p>\n<p>You have just developed your first Node program. <\/p>\n<p>Our server responds to a simple message as a text, however, in practice we need to handle different types of responses. <\/p>\n<p>Let\u2019s look over some of the common response types.<\/p>\n<p>One of the most common responses that you need to handle while developing a Node application is JSON. <\/p>\n<p>Here is how you can send JSON responses.<\/p>\n<p><code lang=\"javascript\"><br \/>\nconst http = require(\"http\");<br \/>\nconst hostname = \"localhost\";<br \/>\nconst port = 3000;<br \/>\nconst server = http.createServer((req, res) => {<br \/>\n res.statusCode = 200;<br \/>\n res.setHeader(\"Content-Type\", \"application\/json\");<br \/>\n res.end('{ \"message\" : \"Hello World \" }');<br \/>\n});<\/p>\n<p>server.listen(port, hostname, () => {<br \/>\n console.log(`Server running at   http:\/\/${hostname}:${port}\/`);<br \/>\n});<br \/>\n<\/code><\/p>\n<p>If you run this code, and navigate to the browser, you should see the following response.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.26.51-PM.png\" alt=\"Nodejs tutorial for beginners step by step\" width=\"893\" height=\"408\" class=\"alignnone size-full wp-image-6903\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.26.51-PM.png 893w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.26.51-PM-300x137.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.26.51-PM-768x351.png 768w\" sizes=\"(max-width: 893px) 100vw, 893px\" \/><\/p>\n<p>Let\u2019s look over how to send HTML as a response. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst http = require(\"http\");<br \/>\nconst hostname = \"localhost\";<br \/>\nconst port = 3000;<br \/>\nconst server = http.createServer((req, res) => {<br \/>\n res.statusCode = 200;<br \/>\n res.setHeader(\"Content-Type\", \"text\/html\");<br \/>\n res.end(<br \/>\n   \"<\/p>\n<h1>Hello World<\/h1>\n<p>This is a HTML response<\/p>\n<ol>\n<li>One<\/li>\n<li>Two<\/li>\n<li>Three<\/li>\n<\/ol>\n<p>\"<br \/>\n );<br \/>\n});<\/p>\n<p>server.listen(port, hostname, () => {<br \/>\n console.log(`Server running at   http:\/\/${hostname}:${port}\/`);<br \/>\n});<br \/>\n<\/code><\/p>\n<p>When you run this code, you should see the following response.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.37.20-PM.png\" alt=\"Nodejs tutorial for beginners step by step\" width=\"874\" height=\"521\" class=\"alignnone size-full wp-image-6904\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.37.20-PM.png 874w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.37.20-PM-300x179.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.37.20-PM-768x458.png 768w\" sizes=\"(max-width: 874px) 100vw, 874px\" \/><\/p>\n<p>Awesome. <\/p>\n<p>Let\u2019s go ahead and create different routes to support multiple responses. <\/p>\n<p>Check out the code shown below.<\/p>\n<p><code lang=\"javascript\"><br \/>\nconst http = require(\"http\");<br \/>\nconst hostname = \"localhost\";<br \/>\nconst port = 3000;<br \/>\nconst server = http.createServer((req, res) => {<br \/>\n res.statusCode = 200;<br \/>\n res.setHeader(\"Content-Type\", \"text\/html\");<br \/>\n switch (req.url) {<br \/>\n   case \"\/home\":<br \/>\n     res.writeHead(200);<br \/>\n     res.end(\"<\/p>\n<h1>This is Home page<\/h1>\n<p>\");<br \/>\n     break;<br \/>\n   case \"\/about\":<br \/>\n     res.writeHead(200);<br \/>\n     res.end(\"<\/p>\n<h1>This is About page<\/h1>\n<p>\");<br \/>\n     break;<br \/>\n   default:<br \/>\n     break;<br \/>\n }<br \/>\n});<\/p>\n<p>server.listen(port, hostname, () => {<br \/>\n console.log(`Server running at   http:\/\/${hostname}:${port}\/`);<br \/>\n});<br \/>\n<\/code><\/p>\n<p>As you can see, we are using switch cases to determine different routes and on each route, we are sending different responses to each route.<\/p>\n<p>Navigate your browser to <strong>localhost:3000\/home<\/strong> to view the response.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.46.49-PM.png\" alt=\"Nodejs tutorial for beginners step by step\" width=\"773\" height=\"421\" class=\"alignnone size-full wp-image-6905\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.46.49-PM.png 773w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.46.49-PM-300x163.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.46.49-PM-768x418.png 768w\" sizes=\"(max-width: 773px) 100vw, 773px\" \/><\/p>\n<p>Navigate your browser to localhost:3000\/about to view the second response.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.46.58-PM.png\" alt=\"Nodejs tutorial for beginners step by step\" width=\"773\" height=\"421\" class=\"alignnone size-full wp-image-6906\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.46.58-PM.png 773w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.46.58-PM-300x163.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/Screenshot-2020-05-15-at-10.46.58-PM-768x418.png 768w\" sizes=\"(max-width: 773px) 100vw, 773px\" \/><\/p>\n<p>Awesome. We built a simple web server in Node. Let&#8217;s jump to the next step.<\/p>\n<h2>Step 3: Node modules and NPM<\/h2>\n<p>Node modules are the basic building block of the Node program.<\/p>\n<p>The node module is a set of functions that can be reused in your application.<\/p>\n<p>Node has built-in modules as well as you can create your node modules. <\/p>\n<p>Some of the famous built-in node modules are <strong>fs, net, http<\/strong>, and many of the popular modules such as <strong>express, nodemailer<\/strong> built on top of these built-in modules. <\/p>\n<p>We can install node modules using the node package manager or called npm.<\/p>\n<p>You can install node modules using the following command. <\/p>\n<p>Open your terminal\/command prompt and run this command. <\/p>\n<p><code><br \/>\nnpm install<br \/>\n<\/code><\/p>\n<p>Or<br \/>\n<code><br \/>\nnpm i<br \/>\n<\/code><\/p>\n<p>For example:<br \/>\n<code><br \/>\nnpm install express<br \/>\n<\/code><\/p>\n<p>You can also install the module and write it in your package.json file using the following command. <\/p>\n<p><code>npm install --save express<\/code><\/p>\n<p>Or<\/p>\n<p><code>npm i --S express<\/code><\/p>\n<p>You can use the following command to uninstall node modules. <\/p>\n<p><code>npm remove <module name><\/code><\/p>\n<p>If you want to remove the module entry from the package.json file, use this command. <\/p>\n<p><code>npm remove --save <module name><\/code><\/p>\n<p>You can create your own node module as well. All you need to do is create a function and export it for the reusability. <\/p>\n<p>For example, consider this code which can act as a node module. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst calc = (a,b,p) => {<br \/>\n    if(a || b || p ) {<br \/>\n        return \"Please provide all parameters\";<br \/>\n    }<br \/>\n    switch(p) {<br \/>\n        case '+': {<br \/>\n            return a+b;<br \/>\n            break;<br \/>\n        }<br \/>\n        case '-': {<br \/>\n            return a-b;<br \/>\n            break;<br \/>\n        }<br \/>\n        case '*': {<br \/>\n            return a*b;<br \/>\n            break;<br \/>\n        }<br \/>\n        case '\/': {<br \/>\n            return a\/b;<br \/>\n            break;<br \/>\n        }<br \/>\n        default:{return;}<br \/>\n    }<br \/>\n}<br \/>\nexports.calc=calc; \/\/very important line<br \/>\n<\/code><\/p>\n<p>You can reuse this module in your code like this: <\/p>\n<p><code lang=\"javascript\"><br \/>\nvar dt = require('.\/mymodule');<br \/>\nconsole.log(dt.calc(10,20,'+'));<br \/>\n<\/code><\/p>\n<p>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 <a href=\"https:\/\/codeforgeek.com\/how-to-create-nodejs-npm-package\/\" target=\"_blank\" rel=\"noopener noreferrer\">this tutorial.<\/a><\/p>\n<p>Node modules are managed by the file called <strong>package.json<\/strong>. This file contains the list of the packages your project is using along with the version number etc. <\/p>\n<p>A typical <strong>package.json<\/strong> file looks like this:<\/p>\n<p><code lang=\"javascript\"><br \/>\n{<br \/>\n \"name\": \"codeforgeek-app-server\",<br \/>\n \"version\": \"1.0.0\",<br \/>\n \"description\": \"\",<br \/>\n \"main\": \"app.js\",<br \/>\n \"scripts\": {<br \/>\n   \"start\": \"node app.js\"<br \/>\n },<br \/>\n \"keywords\": [],<br \/>\n \"author\": \"\",<br \/>\n \"license\": \"ISC\",<br \/>\n \"dependencies\": {<br \/>\n   \"async\": \"^3.1.0\",<br \/>\n   \"axios\": \"^0.19.0\",<br \/>\n   \"bcrypt\": \"^4.0.1\",<br \/>\n   \"chalk\": \"^2.4.2\",<br \/>\n   \"connect-redis\": \"^4.0.4\",<br \/>\n   \"cors\": \"^2.8.5\",<br \/>\n   \"express\": \"^4.17.1\",<br \/>\n   \"mongodb\": \"^3.2.7\",<br \/>\n   \"nconf\": \"^0.10.0\",<br \/>\n   \"nodemailer\": \"^6.3.0\",<br \/>\n   \"pug\": \"^2.0.4\",<br \/>\n   \"reading-time\": \"^1.2.0\",<br \/>\n   \"redis\": \"^2.8.0\",<br \/>\n   \"winston\": \"^3.2.1\"<br \/>\n }<br \/>\n}<br \/>\n<\/code><\/p>\n<p>We also specify details such as project name, version, entry file of the project in the package.json.<\/p>\n<p>All the dependencies that are installed using npm install command are listed in the <strong>package.json.<\/strong> You should always maintain the updated version of package.json while dealing with the packages. <\/p>\n<p>Let&#8217;s jump to the next step.<\/p>\n<h2>Step 4: File system module.<\/h2>\n<p>The <strong>fs<\/strong> 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: <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst fs = require('fs');<br \/>\n<\/code><\/p>\n<p>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.<\/p>\n<p>You can use <strong>fs.readFile()<\/strong> or <strong>fs.readFileSync()<\/strong> method to read files in Node.<\/p>\n<p>For example: Using the readFile() method. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst fs = require('fs');<br \/>\nfs.readFile('.\/lorem.txt', (err, data) => {<br \/>\n  if(err) {<br \/>\n    return console.log('Error occurred while reading file');<br \/>\n   }<br \/>\n  console.log(data.toString());<br \/>\n});<br \/>\n<\/code><\/p>\n<p>Using the <strong>readFileSync()<\/strong> method. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst fs = require('fs');<br \/>\nconst data = fs.readFileSync('.\/lorem.txt'); console.log(data.toString());<br \/>\n<\/code><\/p>\n<p>The simplest approach to check whether the file exists or not is by using the <strong>readFile()<\/strong> function. <\/p>\n<p>However, this function does open the file descriptor and occupies some memory too. <\/p>\n<p>If you just want to check the file existences in the system, I highly recommend the <strong>access()<\/strong> function. Here is the code: <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst fs = require('fs');<br \/>\nconst path = '.\/config.js';<br \/>\nfs.access(path, fs.F_OK, (err) => {<br \/>\n  if (err) {<br \/>\n    console.error(err);<br \/>\n    return;<br \/>\n  }<br \/>\n});<br \/>\n<\/code><\/p>\n<p>The file system module provides three methods to create files:<\/p>\n<ol>\n<li>fs.open()<\/li>\n<li>fs.writeFile()<\/li>\n<li>fs.appendFile()<\/li>\n<\/ol>\n<p><strong>fs.open() <\/strong>method opens a new file or creates a new empty file if it does not exist in the specified path. <\/p>\n<p>It takes the second parameter which acts as a flag such as w for writing, w+ for reading and writing, etc. Code: <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst fs = require('fs');<br \/>\nfs.open('file.txt', 'w', (err, file) => {<br \/>\n  if (err) {<br \/>\n    throw err;<br \/>\n  }<br \/>\n  console.log('Saved!');<br \/>\n});<br \/>\n<\/code><\/p>\n<p><strong>fs.writeFile() <\/strong> method allows you to create or replace files with the content. <\/p>\n<p>If a file exists, it will replace the content with the provided content and if the file does not exist, it will create it. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst fs = require('fs');<br \/>\nfs.writeFile('file.txt', 'Hello Word!', (err) => {<br \/>\n  if (err) {<br \/>\n    throw err;<br \/>\n  }<br \/>\n console.log('Saved!');<br \/>\n});<br \/>\n<\/code><\/p>\n<p><strong>fs.appendFile()<\/strong> method appends the provided content at the end of the file. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst fs = require('fs');<br \/>\nfs.appendFile('file.txt', ' Hello World', (err) => {<br \/>\n  if (err) {<br \/>\n    throw err;<br \/>\n  }<br \/>\n  console.log('Updated!');<br \/>\n});<br \/>\n<\/code><\/p>\n<p>To delete a file, we can use <strong>fs.unlink()<\/strong> method. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst fs = require('fs');<br \/>\nfs.unlink('file.txt', (err) => {<br \/>\n  if (err) {<br \/>\n    throw err;<br \/>\n  }<br \/>\n  console.log('File deleted!');<br \/>\n});<br \/>\n<\/code><\/p>\n<p>To rename a file, we can use the <strong>fs.rename()<\/strong> method. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst fs = require('fs');<br \/>\nfs.rename('newfile.txt', 'oldfile.txt', (err) => {<br \/>\n  if (err) {<br \/>\n    throw err;<br \/>\n  }<br \/>\n  console.log('File Renamed!');<br \/>\n});<br \/>\n<\/code><\/p>\n<p>You can also copy files using the fs.copy() method.<\/p>\n<p><code lang=\"javascript\"><br \/>\nconst fs = require('fs');<br \/>\nfs.copyFile(file.txt', 'copyfile.txt', (err) => {<br \/>\n  if (err) {<br \/>\n    throw err;<br \/>\n  }<br \/>\n  console.log('File is copied!');<br \/>\n}); <\/p>\n<p><\/code><\/p>\n<p>Let&#8217;s jump to the next step.<\/p>\n<h2>Step 5: Express framework<\/h2>\n<p>Express is a popular framework to develop web applications in Node. <\/p>\n<p>Express is widely used and can be used to develop web applications such as Web Server, REST API Server, Streaming engine, etc. <\/p>\n<p>In this section, we are going to learn about express and we will create a simple web server with different routes. <\/p>\n<p>Terminologies we will use in this section are:<\/p>\n<ol>\n<li>route: This means an endpoint. for example facebook.com\/profile so the profile is a route.<\/li>\n<li>middleware: A set of functions that will be executed in the chosen order.<\/li>\n<\/ol>\n<p>Let&#8217;s begin.<\/p>\n<p>Create a new folder and switch to it using a terminal or command prompt. <\/p>\n<p>Create a new node project using the following command.<\/p>\n<p><code><br \/>\nnpm init --y<br \/>\n<\/code><\/p>\n<p>This will create a sample package.json for your project. To install the express module, run the following command. <\/p>\n<p><code>npm install --save express<\/code> <\/p>\n<p>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. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst express = require('express');<br \/>\nconst app = express(); <\/p>\n<p>app.listen(process.env.port || 3000); <\/p>\n<p>console.log('Web Server is listening at port '+ (process.env.port || 3000));<br \/>\n<\/code><\/p>\n<p>In the code shown above, we have required the express module and created a new instance of it. <\/p>\n<p>In the end, we have started our Server using the <strong>listen()<\/strong> function.<\/p>\n<p>Routers are simply an endpoint of a server. <\/p>\n<p>For example, facebook.com\/codeforgeek, here the <strong>codeforgeek<\/strong> is a route. <\/p>\n<p>We need to create routers in our web application to serve different requests. We will create the following routes in our web application.<\/p>\n<ol>\n<li>home<\/li>\n<li>profile<\/li>\n<li>login<\/li>\n<li>logout<\/li>\n<\/ol>\n<p>Express routers allow us to serve different HTTP methods such as GET, POST, PUT, DELETE, HEAD. Here is how to create a router. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst express = require('express');<br \/>\nconst app = express();<br \/>\nconst router = express.Router(); <\/p>\n<p>router.get('\/home', (req,res) => {<br \/>\n  res.send('Hello World, This is home router');<br \/>\n}); <\/p>\n<p>router.get('\/profile', (req,res) => {<br \/>\n  res.send('<br \/>\n    Hello World, This is profile router<br \/>\n  ');<br \/>\n}); <\/p>\n<p>router.get('\/login', (req,res) => {<br \/>\n  res.send('<br \/>\n    Hello World, This is login router<br \/>\n  ');<br \/>\n}); <\/p>\n<p>router.get('\/logout', (req,res) => {<br \/>\n  res.send('<br \/>\n   Hello World, This is logout router<br \/>\n  ');<br \/>\n}); <\/p>\n<p>app.use('\/', router); <\/p>\n<p>app.listen(process.env.port || 3000); <\/p>\n<p>console.log('Web Server is listening at port '+ (process.env.port || 3000));<br \/>\n<\/code><\/p>\n<p>Let&#8217;s run our application, save the file, and run the code using the following command. <\/p>\n<p><code><br \/>\nnode app.js<br \/>\n<\/code><\/p>\n<p>You should see the following message in the terminal. <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/express-app-start.png\" alt=\"Nodejs tutorial for beginners step by step\" width=\"790\" height=\"475\" class=\"alignnone size-full wp-image-6171\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/express-app-start.png 790w, https:\/\/codeforgeek.com\/wp-content\/uploads\/express-app-start-300x180.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/express-app-start-768x462.png 768w\" sizes=\"(max-width: 790px) 100vw, 790px\" \/><\/p>\n<p>Open your browser and visit the routes.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/express-home-routes.png\" alt=\"Nodejs tutorial for beginners step by step\" width=\"793\" height=\"554\" class=\"alignnone size-full wp-image-6172\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/express-home-routes.png 793w, https:\/\/codeforgeek.com\/wp-content\/uploads\/express-home-routes-300x210.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/express-home-routes-768x537.png 768w\" sizes=\"(max-width: 793px) 100vw, 793px\" \/><\/p>\n<p>Here is the profile page. <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/express-profile-page.png\" alt=\"Nodejs tutorial for beginners step by step\" width=\"793\" height=\"554\" class=\"alignnone size-full wp-image-6173\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/express-profile-page.png 793w, https:\/\/codeforgeek.com\/wp-content\/uploads\/express-profile-page-300x210.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/express-profile-page-768x537.png 768w\" sizes=\"(max-width: 793px) 100vw, 793px\" \/><\/p>\n<p>You can also send <a href=\"https:\/\/codeforgeek.com\/render-html-file-expressjs\/\" rel=\"noopener noreferrer\" target=\"_blank\">HTML<\/a>\/JSON\/XML as a response.<\/p>\n<p>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.<\/p>\n<ul>\n<li>Application middleware<\/li>\n<li>Router middleware<\/li>\n<li>Error-handling middleware<\/li>\n<li>Built-in middleware<\/li>\n<li>Third-party middleware<\/li>\n<\/ul>\n<h3>Application middleware<\/h3>\n<p>We can use middleware in the application object of the express. For example: <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst express = require('express');<br \/>\nconst app = express(); <\/p>\n<p>app.use((req, res, next) => {<br \/>\n  console.log('Time:', Date.now());<br \/>\n  next();<br \/>\n}); <\/p>\n<p>app.listen(process.env.port || 3000); <\/p>\n<p>console.log('Web Server is listening at port '+ (process.env.port || 3000));<br \/>\n<\/code><\/p>\n<h3>Router middleware<\/h3>\n<p>In a similar way as application middleware, we can use router middleware. For example: <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst express = require('express');<br \/>\nconst app = express();<br \/>\nconst router = express.Router();<\/p>\n<p>router.use((req, res, next) => {<br \/>\n  console.log('Time:', Date.now());<br \/>\n  next();<br \/>\n});<\/p>\n<p>router.get('\/home', (req,res) => {<br \/>\n  res.send(\"ok\")<br \/>\n});<\/p>\n<p>app.use('\/', router);<br \/>\napp.listen(process.env.port || 3000);<\/p>\n<p>console.log('Web Server is listening at port '+ (process.env.port || 3000));<br \/>\n<\/code><\/p>\n<h3>error-handling middleware<\/h3>\n<p>We can use this middleware to catch errors. <\/p>\n<p><code lang=\"javascript\"><br \/>\napp.use((err, req, res, next) => {<br \/>\n  res.status(500).send('Something broke!')<br \/>\n});<br \/>\n<\/code><\/p>\n<p>Learn more about this function <a href=\"https:\/\/codeforgeek.com\/error-handling-in-express-using-middleware\/\" rel=\"noopener noreferrer\" target=\"_blank\">here<\/a>.<\/p>\n<h3>Built-in middleware<\/h3>\n<p>Express provides some middleware by default such as static, JSON, etc. <\/p>\n<h3>Third-party middleware<\/h3>\n<p>We can use third-party middlewares such as body-parser. Here is how we can install third-party middleware. <\/p>\n<p><code>npm install body-parser<\/code><\/p>\n<p>To use this middleware, we need to require our code and load it. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst express = require('express');<br \/>\nconst bodyParser = require('body-parser');<br \/>\nconst app = express();<br \/>\nconst router = express.Router(); <\/p>\n<p>router.get('\/home', (req,res) => {<br \/>\n  res.send('<br \/>\n   Hello World, This is home router<br \/>\n  ');<br \/>\n}); <\/p>\n<p>router.get('\/profile', (req,res) => {<br \/>\n  res.send('<br \/>\n   Hello World, This is profile router<br \/>\n  ');<br \/>\n}); <\/p>\n<p>router.get('\/login', (req,res) => {<br \/>\n  res.send('<br \/>\n   Hello World, This is login router<br \/>\n  ');<br \/>\n}); <\/p>\n<p>router.get('\/logout', (req,res) => {<br \/>\n  res.send('<br \/>\n   Hello World, This is logout router<br \/>\n  ');<br \/>\n}); <\/p>\n<p>\/\/ add middleware before routes<br \/>\napp.use(bodyParser.json()); <\/p>\n<p>app.use('\/', router); <\/p>\n<p>app.listen(process.env.port || 3000); <\/p>\n<p>console.log('Web Server is listening at port '+ (process.env.port || 3000));<br \/>\n<\/code> <\/p>\n<p>If you are interested in creating your middleware, I recommend you <a href=\"https:\/\/codeforgeek.com\/how-to-write-custom-middleware-for-expressjs\/\" rel=\"noopener noreferrer\" target=\"_blank\">this article.<\/a><\/p>\n<p>We can handle sessions in Express using express-session middleware. We can use this middleware to create, track, and delete sessions. <\/p>\n<p><code><br \/>\nnpm install --save express-session<br \/>\n<\/code><\/p>\n<p>To use this module in our code, load this as a middleware. <\/p>\n<p><code lang=\"javascript\"><br \/>\napp.use(session({secret: 'some secrets'}));<br \/>\n<\/code><\/p>\n<p>Now, we can use <strong>req.session<\/strong> object to create, track, and delete sessions. <\/p>\n<p>To learn more about the session, please read <a href=\"https:\/\/codeforgeek.com\/using-redis-to-handle-session-in-node-js\/\" rel=\"noopener noreferrer\" target=\"_blank\">this<\/a> article.<\/p>\n<p>We can also use external stores such as Redis to store session values instead of storing them in memory. <\/p>\n<p>Let&#8217;s jump to the next step and learn about the integration of databases with Node.<\/p>\n<h2>Step 6: Databases &#8211; MySQL, MongoDB, PostgreSQL and Redis.<\/h2>\n<p>The database is an integral part of any application. You must know how to use it with Node to build a complete application. <\/p>\n<p>We are going to cover the following databases in this section:<\/p>\n<ul>\n<li>MySQL<\/li>\n<li>MongoDB<\/li>\n<li>PostgreSQL<\/li>\n<li>Redis<\/li>\n<\/ul>\n<p>Let\u2019s begin with MySQL.<\/p>\n<h3>MySQL<\/h3>\n<p>MySQL is a very popular SQL database. In this section, we will learn how to connect, query, and use it with NodeJS.<\/p>\n<p>MySQL is a very popular database and has been used in millions of applications. We can use MySQL with Node as well. <\/p>\n<p>We need to install the module name as MySQL to use it with the MySQL database.<\/p>\n<p>You need to have the MySQL database installed in your system before proceeding.<\/p>\n<p>To install the node module to connect with MySQL: <\/p>\n<p><code><br \/>\nnpm install --save mysql<br \/>\n<\/code><\/p>\n<p>Here is how we can establish a connection to the MySQL engine. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst mysql = require(\"mysql\");<\/p>\n<p>const pool = mysql.createPool({<br \/>\n connectionLimit: 100,<br \/>\n host: \"localhost\",<br \/>\n user: \"root\",<br \/>\n password: \"\",<br \/>\n database: \"database_name\",<br \/>\n debug: false,<br \/>\n});<\/p>\n<p>pool.query(\"SELECT * from <table_name> LIMIT 10\", (err, rows) => {<br \/>\n if (err) {<br \/>\n   console.log(\"error occurred during the connection.\");<br \/>\n }<br \/>\n console.log(rows[0]);<br \/>\n});<br \/>\n<\/code><\/p>\n<p>You can execute the queries such as INSERT, UPDATE and DELETE in a similar fashion. Learn more in detail about using <a href=\"https:\/\/codeforgeek.com\/nodejs-mysql-tutorial\/\" rel=\"noopener noreferrer\" target=\"_blank\">Node and MySQL<\/a>.<\/p>\n<p>Let\u2019s learn about MongoDB.<\/p>\n<h3>MongoDB<\/h3>\n<p>MongoDB is a very popular NoSQL database. Learn how to connect, query, and use it with NodeJS.<\/p>\n<p>MongoDB is one of the most popular general-purpose NoSQL database engines. <\/p>\n<p>To integrate MongoDB with Node, you need to install the MongoDB database in your system. <\/p>\n<p>Click <a href=\"https:\/\/www.mongodb.com\/\" rel=\"noopener noreferrer\" target=\"_blank\">here<\/a> to visit the official site and download the latest version of MongoDB. <\/p>\n<p>Assuming you have MongoDB installed, let&#8217;s install the MongoDB driver for Node. <\/p>\n<p><code><br \/>\nnpm install --save mongodb<br \/>\n<\/code><\/p>\n<p>We need to require the module and then connect to the MongoDB instance. Here is the code. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst mongo = require(\"mongodb\");<br \/>\nconst url = \"mongodb:\/\/localhost:27017\/test\";<\/p>\n<p>mongo.connect(url, { useNewUrlParser: true }, (err, db) => {<br \/>\n if (err) {<br \/>\n   console.log(err);<br \/>\n   process.exit(0);<br \/>\n }<br \/>\n console.log(\"database connected!\");<br \/>\n db.close();<br \/>\n});<br \/>\n<\/code><\/p>\n<p>MongoDB runs on port <strong>27017<\/strong>. We can connect to any database we like to work with. <\/p>\n<p>In the code shown above, we are connecting to the <strong>test<\/strong> database. <\/p>\n<p>We are using the <strong>connect()<\/strong> method to establish a connection with the database. Save the code above in a file called <strong>&#8216;app.js&#8217;<\/strong> and run the file: <\/p>\n<p><code><br \/>\nnode app.js<br \/>\n<\/code><\/p>\n<p>You should see output similar to this: <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/mongodb-connection.png\" alt=\"MongoDB connections\" width=\"1175\" height=\"459\" class=\"alignnone size-full wp-image-6197\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/mongodb-connection.png 1175w, https:\/\/codeforgeek.com\/wp-content\/uploads\/mongodb-connection-300x117.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/mongodb-connection-768x300.png 768w, https:\/\/codeforgeek.com\/wp-content\/uploads\/mongodb-connection-1024x400.png 1024w\" sizes=\"(max-width: 1175px) 100vw, 1175px\" \/><\/p>\n<p>In order to store data in the MongoDB database you need to create a <strong>collection<\/strong>. <\/p>\n<p>Think of <strong>collection<\/strong> 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.<\/p>\n<p><code lang=\"javascript\"><br \/>\nconst mongo = require(\"mongodb\");<br \/>\nconst url = \"mongodb:\/\/localhost:27017\/\";<\/p>\n<p>mongo.connect(url, { useNewUrlParser: true }, (err, db) => {<br \/>\n if (err) {<br \/>\n   console.log(err);<br \/>\n   process.exit(0);<br \/>\n }<br \/>\n console.log(\"database connected!\");<br \/>\n var dbo = db.db(\"test\");<br \/>\n dbo.createCollection(\"customers\", (err, result) => {<br \/>\n   if (err) {<br \/>\n     console.log(err);<br \/>\n     process.exit(0);<br \/>\n   }<br \/>\n   console.log(\"collection created!\");<br \/>\n   db.close();<br \/>\n });<br \/>\n});<br \/>\n<\/code><\/p>\n<p>Let&#8217;s try to add some data in the MongoDB collection. <\/p>\n<p>MongoDB stores data in a JSON format. JSON is a key-value based data format widely used across various layers of software. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst mongo = require(\"mongodb\");<br \/>\nconst url = \"mongodb:\/\/localhost:27017\/\";<br \/>\nmongo.connect(url, { useNewUrlParser: true }, (err, db) => {<br \/>\n if (err) {<br \/>\n   console.log(err);<br \/>\n   process.exit(0);<br \/>\n }<br \/>\n let data = { id: 100, name: \"Shahid\" };<br \/>\n var dbo = db.db(\"test\");<br \/>\n console.log(\"database connected!\");<br \/>\n dbo.collection(\"user\").insert(data, (err, result) => {<br \/>\n   if (err) {<br \/>\n     console.log(err);<br \/>\n     process.exit(0);<br \/>\n   }<br \/>\n   console.log(\"records added.\");<br \/>\n   console.log(result);<br \/>\n   db.close();<br \/>\n });<br \/>\n});<br \/>\n<\/code><\/p>\n<p>You can also search for the data inside the collection using the <strong>findOne()<\/strong> function. <\/p>\n<p><code lang=\"javascript\"><br \/>\nconst mongo = require(\"mongodb\");<br \/>\nconst url = \"mongodb:\/\/localhost:27017\/\";<\/p>\n<p>mongo.connect(url, { useNewUrlParser: true }, (err, db) => {<br \/>\n if (err) {<br \/>\n   console.log(err);<br \/>\n   process.exit(0);<br \/>\n }<\/p>\n<p> let data = { id: 100, name: \"Shahid\" };<br \/>\n var dbo = db.db(\"test\");<br \/>\n console.log(\"database connected!\");<\/p>\n<p> dbo.collection(\"user\").findOne({}, (err, result) => {<br \/>\n   if (err) {<br \/>\n     console.log(err);<br \/>\n     process.exit(0);<br \/>\n   }<br \/>\n   console.log(\"Here is the record\");<br \/>\n   console.log(result);<br \/>\n   db.close();<br \/>\n });<br \/>\n});<\/p>\n<p><\/code><\/p>\n<p>After running the code above, you should see a record similar to this. <\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/MongoDB-Find.png\" alt=\"MongoDB find command result\" width=\"980\" height=\"443\" class=\"alignnone size-full wp-image-6199\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/MongoDB-Find.png 980w, https:\/\/codeforgeek.com\/wp-content\/uploads\/MongoDB-Find-300x136.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/MongoDB-Find-768x347.png 768w\" sizes=\"(max-width: 980px) 100vw, 980px\" \/><\/p>\n<p>You can also perform tons of other operations such as query(), sort(), delete() etc. Learn more about <a href=\"https:\/\/codeforgeek.com\/node-mongodb-tutorial\/\" rel=\"noopener noreferrer\" target=\"_blank\">MongoDB<\/a> here.<\/p>\n<p>Let\u2019s proceed towards the next database, PostgreSQL.<\/p>\n<h3>PostgreSQL<\/h3>\n<p>PostgreSQL is a very popular SQL database. Learn how to connect, query, and use it with NodeJS.<\/p>\n<p>PostgreSQL, also referred to as Postgres, is a free and popular relational database system. <\/p>\n<p>Postgres competes with relational databases like MySQL, SQL Server, or MariaDB.<\/p>\n<p>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. <\/p>\n<p>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. <\/p>\n<p><code><br \/>\npsql postgres<br \/>\n<\/code><\/p>\n<p>Create a new user.<br \/>\n<code lang='sql'><br \/>\nCREATE ROLE codeforgeek WITH LOGIN PASSWORD 'somepassword'<br \/>\n<\/code><\/p>\n<p>Give permission to the new user.<br \/>\n<code lang='sql'><br \/>\nALTER ROLE codeforgeek CREATEDB;<br \/>\n<\/code><\/p>\n<p>Now, exit from the current session and login again with your new user credentials. <\/p>\n<p><code><br \/>\npsql -d postgres -U codeforgeek<br \/>\n<\/code><\/p>\n<p>Create a new database.<br \/>\n<code lang=\"sql\"><br \/>\nCREATE DATABASE users;<br \/>\n<\/code><\/p>\n<p>Switch to a new database. <\/p>\n<p><code>c users;<\/code> <\/p>\n<p>Create a new table. <\/p>\n<p><code lang=\"sql\"><br \/>\nusers=> CREATE TABLE profile (<br \/>\n  ID SERIAL PRIMARY KEY,<br \/>\n  name VARCHAR(30),<br \/>\n  email VARCHAR(30)<br \/>\n);<br \/>\n<\/code><\/p>\n<p>Insert some records.<br \/>\n<code lang=\"sql\"><br \/>\nINSERT<br \/>\nINTO profile (name, email)<br \/>\nVALUES<br \/>\n('Jerry', 'jerry@example.com'),<br \/>\n('George', 'george@example.com');<br \/>\n<\/code><\/p>\n<p>Let&#8217;s connect to it using our Node program. Install the dependency.<br \/>\n<code><br \/>\nnpm install --save pg<br \/>\n<\/code><\/p>\n<p>Create an app.js file and add the following code in it.<br \/>\n<code lang=\"javascript\"><br \/>\nconst Pool = require(\"pg\").Pool;<br \/>\nconst pool = new Pool({<br \/>\n user: \"codeforgeek\",<br \/>\n host: \"localhost\",<br \/>\n database: \"users\",<br \/>\n password: \"somepassword\",<br \/>\n port: 5432,<br \/>\n});<\/p>\n<p>\/\/ read information from table<br \/>\npool.query(\"SELECT * FROM profile ORDER BY id ASC\", (error, results) => {<br \/>\n if (error) {<br \/>\n   console.log(error);<br \/>\n   return;<br \/>\n }<br \/>\n console.log(results);<br \/>\n});<\/p>\n<p>\/\/ add a new user profile.<br \/>\nconst name = \"Shahid\";<br \/>\nconst email = \"shahid@codeforgeek.com\";<\/p>\n<p>pool.query(<br \/>\n \"INSERT INTO profile (name, email) VALUES ($1, $2)\",<br \/>\n [name, email],<br \/>\n (error, results) => {<br \/>\n   if (error) {<br \/>\n     console.log(error);<br \/>\n     return;<br \/>\n   }<br \/>\n   console.log(results);<br \/>\n }<br \/>\n);<br \/>\n<\/code><\/p>\n<p>We created a new Pool connection to Postgres. We first executed a SELECT query using the <strong>pool.query()<\/strong> method. The pool connection automatically returns the connection to the pool after executing the query.<\/p>\n<p>Let\u2019s proceed towards the final database in the section. <\/p>\n<h3>Redis<\/h3>\n<p>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.<\/p>\n<p>Redis along with Node.js can be used to solve various problems such as cache server or message broker. <\/p>\n<p>You can install Redis in your system by following the official installation guides. <\/p>\n<p>Once installed, you can run the Redis server using the following command.<\/p>\n<p><code>redis-server<\/code><\/p>\n<p>You should see the following in your terminal.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/05\/Screen-Shot-2016-05-18-at-12.06.02-AM.png\" alt=\"Redis Server\" width=\"1244\" height=\"750\" class=\"alignnone size-full wp-image-2289\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/05\/Screen-Shot-2016-05-18-at-12.06.02-AM.png 1244w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/05\/Screen-Shot-2016-05-18-at-12.06.02-AM-300x181.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/05\/Screen-Shot-2016-05-18-at-12.06.02-AM-768x463.png 768w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/05\/Screen-Shot-2016-05-18-at-12.06.02-AM-1024x617.png 1024w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2016\/05\/Screen-Shot-2016-05-18-at-12.06.02-AM-640x386.png 640w\" sizes=\"(max-width: 1244px) 100vw, 1244px\" \/><\/p>\n<p>To access the Redis command-line interface, run the following command from a separate terminal.<\/p>\n<p><code>redis-cli<\/code><\/p>\n<p>To configure Redis with Node, we need to install the Redis driver.<\/p>\n<p><code>npm i --S redis<\/code><\/p>\n<p>Here is the sample code to connect to the Redis server.<\/p>\n<p><code lang=\"javascript\"><br \/>\nvar redis = require('redis');<br \/>\nvar redisClient = redis.createClient({host : 'localhost', port : 6379});<\/p>\n<p>redisClient.on('ready',function() {<br \/>\n console.log(\"Redis is ready\");<br \/>\n});<\/p>\n<p>redisClient.on('error',function() {<br \/>\n console.log(\"Error in Redis\");<br \/>\n});<br \/>\n<\/code><\/p>\n<p>When you run this command, you should have a connection with the Redis.<\/p>\n<p>You can use set(), get() and other Redis commands to perform various operations.<\/p>\n<p>To dig deeper into Redis, you can visit <a href=\"https:\/\/codeforgeek.com\/node-js-redis-tutorial-installation-commands\/\" rel=\"noopener noreferrer\" target=\"_blank\">this<\/a> tutorial.<\/p>\n<h2>Step 7: Deploying Node application to a Cloud Server<\/h2>\n<p>Let&#8217;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. <\/p>\n<p>Click <a href=\"https:\/\/cloud.digitalocean.com\/droplets\/new\" rel=\"noopener noreferrer\" target=\"_blank\">here<\/a> to go to the DigitalOcean droplet creation screen. <\/p>\n<p>Choose a <strong>$5 plan<\/strong> 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. <\/p>\n<p><code><br \/>\nssh username@dropletip<br \/>\n<\/code><\/p>\n<p>Provide the password given in the email and you are good to go. <\/p>\n<p>Once you are logged in, update the system using the following command. <\/p>\n<p><code>sudo apt-get update<\/code><\/p>\n<p>Install Git. <\/p>\n<p><code>sudo apt-get install git<\/code><\/p>\n<p>Install the latest Node on your Server. <\/p>\n<p><code>curl -sL https:\/\/deb.nodesource.com\/setup_12.x | sudo -E bash - <\/code><\/p>\n<p>sudo apt-get install -y nodejs <\/p>\n<p>Install the PM2 process manager.<\/p>\n<p><code>npm install -g pm2 <\/code><br \/>\nOur server is ready to host our Node applications.<\/p>\n<p>Github is a code hosting platform. Learn how to host your code in the Github platform.<\/p>\n<p>Let&#8217;s push our code to Github. Go to <a href=\"https:\/\/github.com\" rel=\"noopener noreferrer\" target=\"_blank\">Github.com<\/a> and create a new repository. <\/p>\n<p>Copy the repository path. Assuming you have Git installed in your machine. Switch to the project directory and execute these commands one by one. <\/p>\n<p><code><br \/>\ngit init<br \/>\ngit add .<br \/>\ngit commit - m \"first push\"<br \/>\ngit remote add origin << github repo URL >><br \/>\ngit push origin master<br \/>\n<\/code><\/p>\n<p>Login to your server using SSH. <\/p>\n<p><code>ssh yourusername@dropletIP <\/code><\/p>\n<p>Clone the Github project.<br \/>\n<code>git clone<\/code> <\/p>\n<p>Switch to the project directory.<br \/>\n<code>cd project_name <\/code><\/p>\n<p>Install dependencies.<br \/>\n<code>npm install<\/code> <\/p>\n<p>Run the Node project using PM2. <\/p>\n<p>PM2 is a process management tool for Node. Using PM2 we can ensure 99% uptime of your application. <\/p>\n<p><code><br \/>\npm2 start file_name.js<br \/>\n<\/code><\/p>\n<p>Test your application using Droplet IP and port on which your application is running.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2015\/12\/Screen-Shot-2016-03-14-at-11.45.15-PM.png\" alt=\"Running PM2 process manager\" width=\"932\" height=\"73\" class=\"alignnone size-full wp-image-2095\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2015\/12\/Screen-Shot-2016-03-14-at-11.45.15-PM.png 932w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2015\/12\/Screen-Shot-2016-03-14-at-11.45.15-PM-300x23.png 300w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2015\/12\/Screen-Shot-2016-03-14-at-11.45.15-PM-768x60.png 768w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2015\/12\/Screen-Shot-2016-03-14-at-11.45.15-PM-640x50.png 640w\" sizes=\"(max-width: 932px) 100vw, 932px\" \/><\/p>\n<p>Awesome. You have successfully developed and deployed your application. Here is another article related to <a href=\"https:\/\/codeforgeek.com\/hosting-node-js-app-to-digitalocean-server\/\" rel=\"noopener noreferrer\" target=\"_blank\">deployment of application<\/a> in the production server.<\/p>\n<h2>Download this tutorial in a PDF format<\/h2>\n<p>I have created a PDF format of this Node js tutorial for beginners. You can visit this page to download the book.<\/p>\n<h2>Further Study<\/h2>\n<p>We have written a lot of Node js tutorials on different topics, listing some of the best articles for you to read it further.<\/p>\n<p><a href=\"https:\/\/codeforgeek.com\/node-js-redis-tutorial-building-email-verification-system\/\" rel=\"noopener noreferrer\" target=\"_blank\">Building Email Verification System Using Node and Redis<\/a><br \/>\n<a href=\"https:\/\/codeforgeek.com\/microservices-nodejs\/\" rel=\"noopener noreferrer\" target=\"_blank\">Microservices Architecture with Node.js<\/a><br \/>\n<a href=\"https:\/\/codeforgeek.com\/load-balancing-nodejs-servers-nginx\/\" rel=\"noopener noreferrer\" target=\"_blank\">Load Balancing Node.js Application Servers with Nginx<\/a><br \/>\n<a href=\"https:\/\/codeforgeek.com\/url-shortener-node-js-redis\/\" rel=\"noopener noreferrer\" target=\"_blank\">Building a URL Shortener with Node.Js and Redis<\/a><br \/>\n<a href=\"https:\/\/codeforgeek.com\/load-balancing-nodejs-servers-nginx\/\" rel=\"noopener noreferrer\" target=\"_blank\">Load Balancing Node.js Application Servers with Nginx<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This Node js tutorial is designed for beginners to help you learn Node.js step by step. All you need to do is follow this Node.js tutorial stepwise. Each step covers important topics related to Node.js. This Node.js tutorial is divided into 7 steps. We expect you to follow this step by step. We are going [&hellip;]<\/p>\n","protected":false},"author":69,"featured_media":6912,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[14,18],"tags":[],"class_list":["post-6897","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-nodejs","category-tutorial"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Nodejs-tutorial-for-beginners-step-by-step.png",1500,750,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Nodejs-tutorial-for-beginners-step-by-step-150x150.png",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Nodejs-tutorial-for-beginners-step-by-step-300x150.png",300,150,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Nodejs-tutorial-for-beginners-step-by-step-768x384.png",768,384,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Nodejs-tutorial-for-beginners-step-by-step-1024x512.png",1024,512,true],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Nodejs-tutorial-for-beginners-step-by-step.png",1500,750,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Nodejs-tutorial-for-beginners-step-by-step.png",1500,750,false]},"uagb_author_info":{"display_name":"Pankaj Kumar","author_link":"https:\/\/codeforgeek.com\/author\/pankaj\/"},"uagb_comment_info":0,"uagb_excerpt":"This Node js tutorial is designed for beginners to help you learn Node.js step by step. All you need to do is follow this Node.js tutorial stepwise. Each step covers important topics related to Node.js. This Node.js tutorial is divided into 7 steps. We expect you to follow this step by step. We are going&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/6897","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/69"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=6897"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/6897\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/6912"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=6897"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=6897"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=6897"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}