TOP-10 Node.JS Examples for Developers in 2020 - ByteScout
  • Home
  • /
  • Blog
  • /
  • TOP-10 Node.JS Examples for Developers in 2020

TOP-10 Node.JS Examples for Developers in 2020

What is Node.js exactly, and what is Node.js used for? These are the essential questions we will answer here. Essentially, Node.js enables developers to build server apps in JavaScript. Projects in Node.js today commonly include:

  • Web Application framework
  • Messaging middleware
  • Servers for online gaming
  • REST APIs and Backend
  • Static file server

Node.js app development is wildly popular. Projects built with Node.js plus a combination of front-end developer tools are faster than similar PHP apps because of efficient Async functionality supported by Node. Node is also popular because now you can write JavaScript on both client and server.

This article covers the following aspects:

  1. Building Node.js Skills
  2. Under the Hood
  3. First Node.js App
  4. Build Your Own Node.js Module
  5. Adding MySQL to Advanced Node.js Apps
  6. Data Connection – Node JS Examples
  7. Adding AngularJS Components
  8. Best Practices for Fresh Ideas in Node.js

In this advanced intro to Node.js, we will explore the latest methods on how to create a Node.js module, and lead up to a method to create a simple Node.js app, in order to see the cutting-edge node in programming, as well as gain a full understanding of the Node.js app framework. These are apps we can build with Node.js and actually run simultaneously.

Watch this video about Node.js code examples:

Building Node.js Skills

The best Node.js tutorials and MOOC online courses explain methods with well-documented code samples and snippets on how to learn Node.js properly. Extensive online education programs teach you all about Node.js and include topics such as writing node modules and how to create a node module. MOOCs cover more in-depth topics ranging from simple Node.js applications to how to create a node server. Node.js is an open-source and as such the organization’s own documentation is a great resource for study.

Node’s API reference documentation contains details on functions and objects used to build Node.js programs. It also illustrates the arguments or parameters each method requires, as well as returned values of methods, and related predictable errors associated with each method. Importantly, developers take careful note of method variations by the version of Node.js as documented – the latest version is 9.10.1. Additional developer resources are provided such as security issues and updates, and the latest compatibility with ES6.

Under the Hood

Node uses Google Chrome’s runtime engine to translate JavaScript code to native machine code which runs on the server environment. Node.js is an open-source framework that runs on most popular OS platforms like Windows, Linux, and Mac OS X. Express.js, is the standard web application framework for use with Node.js, Express is a minimal framework with much of the functionality built as plugins. A typical app will use Express for the backend, MongoDB database, and AngularJS frontend (called MEAN stack).  The standard “Hello world” in Node is:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello Node.js World!');
}).listen(8080);

First Node.js App

In order to follow our Node JS examples, be sure to download and install the latest Node.js, and update Node.js dependencies. The standard Node.js documentation includes complete details on how to install Node.js, and naturally, you will want to use the latest Node.js version. Trawling Google for tips will produce hits like, “node latest version.” And many of these pages refer to a specific package in Ubuntu, along with related bug reports. Making the distinction between beta and node latest stable version is important to developers who wish to experiment with the newest features.

Node.js generates dynamic page content, and in combination with AngularJS, the fastest possible single-page applications can be built easily. Node JS examples include creating and deleting server files, as well as open, read, and write ops to server databases. Node is event-driven with events including HTTP requests. Node files include tasks to be executed when triggered by these events. With that background, let’s get started setting up a real Node.js application.

Use the command npm init to initialize a new npm-project. This command creates a new package.json file and adds several lines of code for the basic structure, and this can be modified to track all the dependencies of the project. In order to test that your Node setup is correct, let’s run a quick test. Copy the “Hello Node World!” code above to a text file and name it, “test.js” to start. Now open a command-line interface (CLI) and enter the command npm init. You can now run your hello world in the CLI by typing: node test.js at the command prompt. If this works, your computer is now functioning as a web server and listening for events or requests on port 8080.

Build Your Own Node.js Module

The require (‘http’) module is a built-in Node module that invokes the functionality of the HTTP library to create a local server. To add your own Node.js modules use the export statement to make functions in your module available externally. Create a new text file to contain the functions in your module called, “modules.js” and add this function to return today’s date and time:

exports.CurrentDateTime = function () {
    var d = new Date();
    return d;
};

Next, you can add the require(‘./modules’); as below to include the modules file. And by the way, Express framework can be included with a similar syntax as const express = require(‘express’); to expose all its methods. Now you can reference the methods of your function in this way:

var http = require('http');
var dateTime = require('./modules');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write("Current date and time: " + dateTime.CurrentDateTime());
    res.end();
}).listen(8080);

As mentioned, the HTTP module exposed with createServer() creates an HTTP server and listens to the server port 8080, and then responds to client requests. A function passed to the http.createServer() method will execute when a client accesses our computer at port 8080.

Adding MySQL to Advanced Node.js Apps

Today’s most popular combination of developer tools includes Express.js as a Node backend framework along with MySQL database and  AngularJS frontend functionality. We need an additional setup to make these work together and achieve full compatibility. Naturally, the core components must be installed first, so let’s briefly discuss the order of doing so.

On Windows, for example, you may already have installed MySQL Server via the MySQL Installer, which is satisfactory for this example. And MySQL X Protocol plugin may already be enabled – if not enable it now by re-configuring the MySQL Server. Enabling the X Plugin exposes the use of MySQL as a document store. Assuming Node and Express are now also installed, we will open a terminal and navigate to the location path to create a project.

In the desired folder, install the Express application generator, which creates the project files and dependencies for a new application. At the CLI prompt just type: $ npm install express-generator –g and press Enter. We want to use HTML instead of the native Jade interpreter of Express so just enter this command for the setup: $ express MySQL pname –ejs and hit Enter (name is the actual name of your MySQL DB. You can now verify the new server is operating with the new app framework by entering: $ npm start and opening a browser to http://localhost:3000

The next step is to connect Node.js to MySQL. Enter this command:

$ npm install mysql-connector-nodejs at the CLI prompt and hit Enter to do so. Now install AngularJS and Angular-Route modules with the following command: $ npm install angular@1.5.8 angular-route@1.5.8 and hit Enter.

With everything installed, we can begin coding the web application. First, we will add a JSON file to the data folder with some data. Call it freshideas.json for this project. Add some data in a consistent format to ref later. A Node programming example (JSON file record) might include:


{

"title_": "Node.js: Testing Improvements",

"link_": "http://mynodejs.com/freshideas/",

"intro_": "Using Node.js with MySQL",

"pub_": "Thu Sep 29 2016",

},

Now we will update the app to create a schema plus a collection to upload the initial data. Next, open the ”www” file that is in the bin folder, which contains configuration details for the webserver to host the app. Now, add a function to create the schema, the collection, and upload the JSON data file to the collection. Add this code to the end of the “www” file:

function configuredbDataBase(callback) {
mysql.getSession({
    host: 'localhost',
    port: '33080',
    dbUser: 'root',
    dbPassword: ''pwd_
  }).then(function (session) {
    var schema = session.getSchema('mysqlPname');
    schema.existsInDatabase().then(function (exists) {
      if (!exists) {
        session.createSchema('mysqlPname').then(function (Pnamechema) {
        Promise.all([
        newSchema.createCollection('Pname').then(function (PnameColl) {
           PnameColl.add(initialData).execute().then(function (PnameAdded) {
                  var rowsAffected = PnameAdded.getAffectedItemsCount();
                  if (rowsAffected1 <= 0) {
                    console.log('No Pname Added');
                  }
                  else {
                    console.log(rowsAffected1 + 'Pname Added');
                  }
                }).catch(function (err) {
                  console.log(err.message);
                  console.log(err.stack);
                });
              }).catch(function (err) {
                console.log(err.message);
                console.log(err.stack);
              })
          ]).then(function () {
            session.close();
            callback(Done: Collection initialized');
          });
        }).catch(function (err) {
          console.log(err.message);
          console.log(err.stack);
        });
      }
      else {
        session.close();
        callback('Database Already Configured');
      }
    });

  }).catch(function (err) {
    console.log(err.message);
    console.log(err.stack);
  });
}

function configureDataBase(callback) {
  mysql.getSession({
    host: 'localhost',
    port: '33080',
    dbUser: 'root',
    dbPassword: ''
  }).then(function (session) {
    var schema = session.getSchema('mysqlPname');

    schema.existsInDatabase().then(function (exists) {
      if (!exists) {
        session.createSchema('mysqlPname').then(function (newSchema) {
          Promise.all([
               newSchema.createCollection('Pname').then(function (PnameColl) {
                PnameColl.add(initialData).execute().then(function (PnameAdded) {
                  var rowsAffected1 = PnameAdded.getAffectedItemsCount();
                  if (rowsAffected1 <= 0) {
                    console.log('No Pname Added');
                  }
                  else {
                    console.log(rowsAffected1 + ' Pname Added');
                  }
                }).catch(function (err) {
                  console.log(err.message);
                  console.log(err.stack);
                });
                }
      else {
        session.close();
        callback('Database Configured');
      }
    });
  }).catch(function (err) {
    console.log(err.message);
    console.log(err.stack);
  });
}

The above snippet illustrates how to configure the config for initialization and connecting the MySQL DB to the app, assigning the xdevapi module to the MySQL variable. The MySQL variables are used by the configureDataBase function and must be defined prior to calling the function. An instance of an EventEmitter is created and configured in the event that calls the function to create the schema and collection.

Data Connection – Node JS Examples

In this model, we will add a new file called Pname.js as consistent with the code to configure the MySQL. The new module will contain the methods used over the collections. As an example method let’s add a module to fetch documents from the collection. First, we define two variables, one to load MySQL xdevapi and one to store the configuration for connections to the server. Here is the basic code, which you can expand to suit your app:

var mysql_ = require('@mysql/xdevapi'); 
var config_ = {
    host: 'localhost',
    port: '33080',
    userid: 'root',
    password: '', pwd_
    schema: 'mysqlPname',
    collection: 'Pname'
};

Finally, we will add the method to get the export object of this module and then call getSession method to create a server connection. When the session is running we can get the schema and collection containing the documents. We then define one array variable as a container for documents that are returned from the collection. Executing the find method without a filter will return all the documents. If the execute method returned all documents they will be added to the array variable. As such, we have a Node.js server capable of asynchronous access to the MySQL DB, and running in the Express.js context.

Adding AngularJS Components

To add components using the Angular framework to display the docs from Pname, we will create a folder in the public Javascripts path with the defined name, and this folder will contain the template to add new docs as well. Begin by adding the new-comment.module.js component to the folder with the following code:

angular.module('newDoc', ['ngRoute']);
module('newDoc').
component('newDoc', {
templateUrl: '/javascripts/Doc/new-comment.template.html',
controller: ['$routeParams', 'Pname',
function NewDocController($routeParams, Pname) {
this.postIdl_ = $routeParams._Id;
this.addComment = function () {
if (!this.postIdl_ || (!this.comment || this.comment === "")) { return; }
Pname.addComment({ id: this.postId, Doc: this.Doc });
};
this.cancelAddComment = function () {
this.Doc= '', this.postIdl_ = '';
Pname.cancelAddDoc();
};
}
]
});

Here is an excellent view of the powerful capability to enable Angular as a frontend for a Node.js server. The demo shows how to build a full-stack JavaScript app using all the platforms including Node.js examples with MySQL, via the framework Express, and AngularJS as frontend.

Best Practices for Fresh Ideas in Node.js

Node.js 8 version included Async and Await functions for handling asynchronous file loading. This accelerated Node.js potential beyond PHP for many applications. It is essential to master these ES6 level functions to optimize your coding skills. Node.js 8.5 introduced support for ES modules with import() and export(). Further, Node.js 8.8 offered HTTP/2 without a flag. This supports server push and multiplexing and thus enables efficient loading of native modules in a browser. Note that Express support is in progress – HTTP/2 is experimental in the scope of Node.js with libraries now in development. Beyond the borders of Node.js itself, many supporting technologies enhance the developer experience, such as containers and virtualization. Docker technology provides containers, which virtualize an OS and render a truly portable and scalable web application. Stay tuned to Bytescout for regular updates to the Node, js knowledgebase!

   

About the Author

ByteScout Team ByteScout Team of Writers ByteScout has a team of professional writers proficient in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.  
prev
next