NodeJS – Linux Hint https://linuxhint.com Exploring and Master Linux Ecosystem Fri, 05 Mar 2021 03:11:33 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.2 How to Build A Simple Blog With Hexo Static Site Generator https://linuxhint.com/build-simple-blog-ssg/ Tue, 02 Mar 2021 13:50:05 +0000 https://linuxhint.com/?p=92459 In the modern age, websites are the building blocks of information. From enterprise, eCommerce, social websites to simple blogs, websites allow people to share ideas and thoughts.

This tutorial will show you how you can set up a simple blog using a static site generator that is very fast and easy to use.

What Is An SSG?

SSG, or Static Site Generator, is a web application that converts the dynamic content on a webpage into static content usually stored locally. Static site generators do not require databases and backends, thereby eliminating the need to learn how to code. It mainly focuses on writing and presenting the content.

SSG vs. CMS

The most popular way to create websites and manage content is using CMS or Content management systems such as WordPress, Drupal, Joomla, etc.

CMS systems work by creating and managing content directly using an interactive interface. Since data in a CMS is retrieved from the database, CMSs are very slow as the content is fetched and served as dynamic content. CMS systems are also prone to security vulnerabilities as they rely on external plugins written by other developers to increase functionality.

On the other hand, static site generators work by creating content offline mediums such as text editors and renders the final page view upon publication. Since the content is locally-rendered, with no need for a database, the page renders faster, and load speeds are incredibly fast.

Static site generators are made of pre-compiled code that acts as an engine to render the published content.

How to Build a Static Blog With Hexo

One of the popular choices for building a static site is Hexo.

Hexo is a simple, fast, and powerful SSG application written in NodeJS. Although there are other choices for building a static site, Hexo allows you to customize your site and integrate various tools.

Let us look at how we can set up a simple static site with Hexo.

Installing Hexo

Before we can build a site, we need to set up hexo requirements and install it. For this, we require NodeJS and git.

Start by updating your system:

sudo apt-get update
sudo apt-get upgrade

Once you have your system up to date, install git

sudo apt-get install git

Next, install nodejs from nodesource using the command:

curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
apt-get install -y nodejs

Once you have Nodejs installed, we can proceed to install hexo using the command:

npm install -g hexo-cli

 Working with Hexo

Once you have installed hexo, you can create a site and publish content. Let us look at how to work with Hexo. Keep in mind that this is a quick, simple guide. Refer to the documentation to learn more.

Creating a site

To create a new hexo site, use the command below:

hexo init HexoSite
cd HexoSite
npm install

Understanding Hexo Directory structure

Once you initialize a new Hexo site, you will get a directory structure such as the one below:

-rw-r--r-- 1 cs cs 0 Feb 8 20:51 _config.landscape.yml

-rw-r--r-- 1 cs cs 2439 Feb 8 20:51 _config.yml drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 node_modules

-rw-r--r-- 1 cs cs 615 Feb 8 20:51 package.json

-rw-r--r-- 1 cs cs 56716 Feb 8 20:51 package-lock.json drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 scaffolds drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 source drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 themes

The first file is the _config.yml contains all the settings for your site. Ensure to modify it before deploying your site because it will contain default values.

The next file is the package.json file that contains the NodeJS application data and configurations. Here, you will find installed packages and their versions.

You can learn more about the package.json from the resource page below:

https://docs.npmjs.com/cli/v6/configuring-npm/package-json

Creating a Blog

To create a simple blog in hexo, use the command:

hexo new blog “Hello World Blog”

Once created, you can file the markdown file under /source/_posts directory. You will need to use Markdown markup language to write content.

Creating a new page

Creating a page in Hexo is simple; use the command:

hexo new page “Page-2

The page source is located under /source/Page-2/index.md

Generating and Serving content

Once you publish your content on hexo, you will need to run the application to generate the static content.

Use the commands below:

$ hexo generate

INFO Validating config

INFO Start processing

INFO Files loaded in 966 ms

INFO Generated: archives/index.html

INFO Generated: Page-2/index.html

INFO Generated: archives/2021/index.html

INFO Generated: index.html

INFO Generated: archives/2021/02/index.html

INFO Generated: js/script.js

INFO Generated: fancybox/jquery.fancybox.min.css

INFO Generated: 2021/02/08/Hello-World-Post/index.html

INFO Generated: css/style.css

INFO Generated: 2021/02/08/hello-world/index.html

INFO Generated: css/fonts/FontAwesome.otf

INFO Generated: css/fonts/fontawesome-webfont.woff

INFO Generated: css/fonts/fontawesome-webfont.eot

INFO Generated: fancybox/jquery.fancybox.min.js

INFO Generated: css/fonts/fontawesome-webfont.woff2

INFO Generated: js/jquery-3.4.1.min.js

INFO Generated: css/fonts/fontawesome-webfont.ttf

INFO Generated: css/images/banner.jpg

INFO Generated: css/fonts/fontawesome-webfont.svg

INFO 19 files generated in 2.08 s

To serve the application, run the command:

$ hexo server INFO Validating config INFO Start processing INFO Hexo is running at http://localhost:4000 . Press Ctrl+C to stop.

 Conclusion

This quick and simple introduction has shown you how to use the Hexo static site. If you need more information on how to work with Hexo, please refer to the main documentation provided below:

https://hexo.io/docs ]]> How to Authorize Users Using Google OAuth in Node.js https://linuxhint.com/authorize-users-using-google-oauth/ Tue, 02 Feb 2021 19:17:38 +0000 https://linuxhint.com/?p=88770

Open Authorization, also known as OAuth, is a protocol used to authorize a user on your website using some third-party service like Google, Github, Facebook, etc. The third-party service shares some data (name, email, profile picture, etc.) with your website and then authorizes the user on its behalf without managing the passwords and usernames for your website, and saving the users a lot of extra trouble.

How OAuth Works

When a user clicks on “Login with Google”, it takes the user to the Google OAuth consent page. When the user agrees to the consent and authenticates his identity on Google, Google will contact your website as a third party service and authorize the user on its behalf and share some data with your website. In this way, the user can be authorized without managing the credentials for your website separately.

Implementing Google OAuth using Node.js

Almost all the programming languages provide different libraries to implement google oauth to authorize users. Node.js provides ‘passport’ and ‘passport-google-oauth20’ libraries to implement google oauth. In this article, we will implement an oauth protocol to authorize users to use node.js.

Create a Project on Google

The first step to implement Google OAuth is to create a project on the google developer console for your website. This project is used to get the API keys used to make requests to Google for open authentication. Goto the following link and create your project.

https://console.developers.google.com

Configuring Google Project

After you create the project, go into the project and select “OAuth consent screen” from the left side menu.

Click on the ‘create’ button and provide all the details of your project. Click “Save and Continue” to move on.

Now provide the scope of your project. Scopes are the types of permissions to access the user’s data from a google account. You need to set up the permissions to get specific user data from your google account. Click “Save and Continue.”

Now add the test users to the project if you want. Test users are the only allowed users who can access your web application in Testing mode. For now, we will not enter any test user and click “Save and Continue” to move on to the summary page of the project.

Review your project on the summary page and save the configuration. Now we will generate credentials for our project. Select the ‘Credentials’ tab on the left side menu and click on the ‘Create credentials’ button on top to generate OAuth 2.0 Client IDs.

From the dropdown menu, select ‘OAuth client ID’ and specify the type of application as ‘Web application’ and your application’s name.

On the same page, we have to provide two URIs, the ‘Authorized Javascript Origins’ and the ‘Authorized redirect URIs’. The ‘Authorized javascript origins’ is the HTTP origin of your web application, and it can not have any path. The ‘Authorized redirect URIs’ is the exact URI with a path where the user will be redirected after google authentication.

After entering all the required entries, click on ‘create’ to create OAuth credentials.

Initiating Node.js Project

So far, we have created a google project to authorize users for our application using google. Now we are going to initiate the node.js project to implement oauth. Create a directory named ‘auth’ and initiate the express project.

ubuntu@ubuntu:~$ mkdir auth

ubuntu@ubuntu:~$ cd auth

ubuntu@ubuntu:~$ npm init -y

Installing Required npm Packages

To implement Google OAuth using node.js, we need to install some npm packages. We will use ‘passport’, ‘express’, ‘path’, and ‘passport-google-oauth20’. Install these packages using npm.

ubuntu@ubuntu:~$ npm install express passport passport-google-oauth20 path

Writing Node.js Code

First of all, we will write two simple html web pages, the one with a button, and authorize the user when clicked on the button. The second page will be authorized, and the user will be redirected to the authorized page after authorization. Create a file ‘public/index.html’.

<html>

  <head>

    <title>OAuth</title>

  </head>

  <body>

    <a href=/google/auth”>Authorize Here</a>

  </body>

</html>

Now create a file ‘public/success.html’ with the following content.

<html>

  <head>

    <title>OAuth</title>

  </head>

  <body>

    <h1>Authorized</h1>

  </body>

</html>

After creating web pages, now we will write code to authorize the users to use google oauth. Create a file ‘index.js’.

// importing required packages


const express = require(‘express’);

const passport = require(‘passport’);

const path = require(‘path’);

const GoogleStrategy = require(‘passport-google-oauth20’).Strategy;


const app = express();


// defining parameters


// client id is the parameter that we will get from the google developer console

CLIENT_ID=”xxxxxxx”;


// client secret will also be taken from the google developer console

CLIENT_SECRET=”xxxxx”;


// user will be redirected to the CALLBACK_URL after authorization

CALLBACK_URL=”http://localhost:8000/authorized”;


// port number must be the same as defined in the developer console

PORT=8000;


// configuring passport middleware


app.use(passport.initialize());

app.use(passport.session());


passport.serializeUser( function(id, done) {

  done(null, id);

});


passport.deserializeUser( function(id, done) {

  done(null, id);

});


// following middleware will run whenever passport. Authenticate method is called and returns different parameters defined in the scope.


passport.use(new GoogleStrategy({

  clientID: CLIENT_ID,

  clientSecret: CLIENT_SECRET,

  callbackURL: CALLBACK_URL

  },

  async function(accessToken, refreshToken, profile, email, cb) {

    return cb(null, email.id);

  }

));




// serving home page for the application

app.get(/’, (req, res) =>

{

  res.sendFile(path.join(__dirname + ‘/public/index.html’));

});


// serving success page for the application

app.get(/success’, (req, res) =>

{

  res.sendFile(path.join(__dirname + ‘/public/success.html’));

});


// user will be redirected to the google auth page whenever hits the ‘/google/auth’ route.


app.get(/google/auth’,

  passport.authenticate(‘google’, {scope: [‘profile’, ‘email’]})

);


// authentication failure redirection is defined in the following route


app.get(/authorized’,

  passport.authenticate(‘google’, {failureRedirect: ‘/}),

  (req, res) =>

  {

    res.redirect(/success’);

  }

);


// running server


app.listen(PORT, () =>

{

  console.log(“Server is running on Port ” + PORT)

})

Testing Google OAuth

Now our application is ready, and we can test whether it authorizes the users using google oauth. Go to the root directory and run the application.

ubuntu@ubuntu:~$ node index.js

Now enter the url of your application into the browser.

http://localhost:8000

It shows the home page with an anchor tag.

When we click on the ‘Authorize Here’, it will redirect to the google oauth page.

Your application name ‘Test’ is displayed on the Google authentication page. When you authorize your account, it will take you to the authorized page.

Conclusion

Managing usernames and passwords for different web applications is not a happy task for users. Many users leave your web application without registering their account just because they do not want to manage credentials. The authorization process on your web application or website can be simplified by using third-party services like Google, Facebook, etc. These services authorize users on their behalf, and the user does not need to manage credentials separately. In this article, we have implemented the google oauth protocol to authorize users to use Node.js.

]]>
Introduction to Making GraphQL APIs and Apps in Node.js https://linuxhint.com/graphql-apis-apps-node-js/ Sun, 24 Jan 2021 23:02:11 +0000 https://linuxhint.com/?p=87550

The communication and data transfer between the front end and backend of any application occurs through APIs (Application Programming Interface). There are many different types of APIs used to communicate between the front and back-end applications like RESTful API, SOAP API, GraphQL API, etc. The GraphQL API is a relatively new technology, and it is much faster than other types of APIs available. Fetching data from the database using GraphQL api is much faster than the REST API. While using GraphQL API, the client has control to fetch only the required data instead of getting all the details; that is why GraphQL API works faster than REST API.

Installing Packages

We will build a node.js application using GraphQL API, so we need to install node.js and npm for this before starting the project.

ubuntu@ubuntu:~$ sudo apt-get update -y

ubuntu@ubuntu:~$ sudo apt-get install nodejs

ubuntu@ubuntu:~$ sudo apt-get install npm

Setting up Project

We will use the ‘express’ framework from node.js to build our application. Create a directory named ‘graphql’ and initiate the project.

ubuntu@ubuntu:~$ mkdir graphql

ubuntu@ubuntu:~$ cd graphql/

ubuntu@ubuntu:~$ npm init -y

MongoDB Setup

In our GraphQL project, we will use MongoDB as our database. MongoDB is a schemaless database and stores data in the form of key pairs. In order to install mongoDB, follow the given steps.

Import the public GPG key for MongoDB.

ubuntu@ubuntu:~$ wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -


Create the list file for mongodb.

ubuntu@ubuntu:~$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

Update local repositories.

ubuntu@ubuntu:~$ sudo apt-get update -y

Install mongodb package.

ubuntu@ubuntu:~$ sudo apt-get install -y mongodb-org

Start and enable mongod.service.

ubuntu@ubuntu:~$ sudo systemctl start mongod.service

ubuntu@ubuntu:~$ sudo systemctl enable mongod.service

Installing npm Modules

For our GraphQL application, we need to install some npm packages. We will install cors, express, body-parser, mongoose, etc.

ubuntu@ubuntu:~$ cd graphql/

ubuntu@ubuntu:~$ npm install cors express body-parser mongoose --save

To create a GraphQL api, we need to install an extra npm package named ‘apollo-server-express.’ This npm package is used to run graphQL server with all Node.js HTTP frameworks like ‘express.’

ubuntu@ubuntu:~$ npm install apollo-server-express --save

Defining MongoDB Schema

Now we have our environment set up for our GraphQL application in Node.js, and it is time to define a schema for our application. Create a file ‘models/student.js’ in the project root directory.

// defining student schema

const mongoose = require(‘mongoose’);

const studentSchema = new mongoose.Schema({

     name: {

          type: String,

          required: true

     },

     class: {

          type: Number,

          required: true

     },

     major: {

          type: String,

          required: true

     }

}, {

     timestamps: true

});

const Student = mongoose.model(‘Student’, studentSchema);

module.exports = { Student, studentSchema }

In the above-defined schema, every student must have a name, class, and major.

Building GraphQL API

After creating the Student schema, we will now build GraphQL API. Create a ‘schema.js’ to write GraphQL parameters. There are two parameters, ‘types’ and ‘resolvers,’ used in GraphQL API. In ‘types,’ we will specify our schema, the queries (e.g., Making GET requests), and mutations (e.g., Making UPDATE or DELETE requests) to the specified schema. We will write the different methods defined in ‘types’ to link the queries and mutations with the database in ‘resolvers.’

// importing schema and module

const { gql } = require(‘apollo-server-express’);

const Student = require(‘./models/student’).Student;

// Defining Schema, Query, and Mutation Type

const typeDefs = gql `

   type Student {

      id: ID!,

      name: String!,

      class: Int!,

      major: String!

   }


   type Query {

      getStudents: [Student],

      getStudentById(id: ID!): Student

   }


   type Mutation {

      addStudent( name: String!, class: Int!, major: String! ): Student

      updateStudent( name: String!, class: Int!, major: String! ): Student

      deleteStudent( id: ID! ): Student

   }`


// Defining Resolvers


const resolvers = {

   Query: {

      getStudents: (parent, args) => {

         return Student.find({});

      },

      getStudentById: (parent, args) => {

         return Student.findById(args.id);

      }

   },

   Mutation: {

      addStudent: (parent, args) => {

         let student = new Student({

            name: args.name,

            class: args.class,

            major: args.major

         });

         return student.save();

      },

      updateStudent: (parent, args) => {

         if(!args.id) return;

         return Student.findOneAndUpdate({

            _id: args.id

         },

         {

            $set: {

               name: args.name,

               class: args.class,

               major: args.major

            }

         },

         { new: true }, (err, Student) => {

            if(err) {

               console.log(err);

            } else {};

         })

      }

   }

}


module.exports = {

   typeDefs,

   resolvers

}

Creating GraphQL API Server

Now we are almost done creating the GraphQL Application. The only step left is to create the server. Create a file named ‘app.js’ to configure server parameters.

// importing required packages


const express = require(‘express’);

const mongoose = require(‘mongoose’);

const bodyParser = require(‘body-parser’);

const cors = require(‘cors’);

const { ApolloServer } = require(‘apollo-server-express’);


// importing schema


const { typeDefs, resolvers }= require(‘./schema’);


// connecting to MongoDB


const url = “mongodb://127.0.0.1:27017/students”;

const connect = mongoose.connect(url, { useNewUrlParser: true });

connect.then((db) => {

   console.log('Connection Successful');

}, (err) => {

   console.log(err);

});


// creating server


const server = new ApolloServer({

   typeDefs: typeDefs,

   resolvers: resolvers

});

const app = express();

app.use(bodyParser.json());

app.use(*, cors());

server.applyMiddleware({ app });

app.listen( 8000, () =>

{

   console.log('listening to 8000');

})

Testing the GraphQL API

We have our graphQL server up and running on port 8000, and it is time to test the GraphQL API. Open the GraphQL webpage in the browser by visiting the following url.

http://localhost:8000/graphql

And it will open the following webpage.


Add the student to the database using graphQL API.


Similarly, add more students, and after adding the student, get all the students using GraphQL API.


Note the ID of any of the Students and get the specific student using its id.

Conclusion

Fetching data from the database using the standard REST API makes the query slow as sometimes we get more data than required. Using GraphQL, we can fetch exactly the required data that makes the GraphQL API faster. In this demo project, we only have a single schema, so we have created GraphQL API for that single schema. Also, we have defined three to four methods for the schema. You can create more than one query or mutations according to your application.

]]>
How to Deploy GraphQL Application Using Node.js on EC2 Server https://linuxhint.com/deploy-graphql-application-ec2-server/ Wed, 20 Jan 2021 10:06:36 +0000 https://linuxhint.com/?p=86891 GraphQL, also known as Graph Query Language, established and maintained by Facebook, is a query language used for APIs. It is built using JavaScript, Scala, Java, and Ruby programming languages. Its basic purpose is to ask for the data from server to client.GraphQL aggregates the data from different sources. Aggregation is the process of filtering data on the server side and then sending the filtered data to the client. Without aggregation, we send all the data to the client, and then the data is filtered at the client-side. This makes the system slow, and we can improve the efficiency of an API by using GraphQL. Here we will learn to deploy a simple GraphQL application using node.js on an EC2 server.

Installing Required Packages

The first step to deploy your graphQL application is to ready your server by installing the required packages. Log in to the server using SSH.

ubuntu@ubuntu:~$ ssh ubuntu@IPAdress -i KeyPair.pem

NOTE: Make sure the security group of the instance is configured to allow connection from port 22 and the private key file has 400 permission.

Update Ubuntu repositories.

ubuntu@ubuntu:~$ sudo apt-get update -y

Now install node.js and npm on your ubuntu server.

ubuntu@ubuntu:~$ sudo apt-get install nodejs -y
ubuntu@ubuntu:~$ sudo apt-get install npm -y

Verify the installation by checking the version of node.js and npm.

ubuntu@ubuntu:~$ node -v
ubuntu@ubuntu:~$ npm -v

Move GraphQL Application to EC2 Server

The EC2 instance is ready to deploy graphQL applications in node.js. Now we will move our code to the EC2 instance. Two common ways to copy the code to the server are listed below and will be discussed here.

  • Copy code using scp command
  • Clone application code from Github, Gitlab, or Bitbucket

Copy Application Using scp Command

In order to copy your application to the EC2 server using the scp command, First of all, remove the ‘node_modules’ directory from your graphQL application. This directory has all the npm packages required to run the application. We will install these packages later before starting the graphQL application. Now compress the project directory into a zip file. After creating the zip file, we will move the project zip file to the server. Linux and windows have different methods to create a zip file.

Windows

In windows, right-click on the application root directory and go to the ‘send to’ option. It will open a submenu. Click on the ‘Compressed (zipped) folder’ to create a zip file of the graphQL application.

Linux or Mac

In Linux or Mac OS, we will use the ‘zip’ command to create a zip file of the project.

ubuntu@ubuntu:~$ zip -r graphQL.zip graphQL

The above command will generate the graphQL.zip file of the graphQL directory.

Upload Application to the Server

Now we have a zip file of our application, and we can upload the zip file to the server by using the scp command.

ubuntu@ubuntu:~$ scp -i KeyPair.pem graphQL.zip ubuntu@IPAddress:~/

The above command will move the project zip file to the remote server’s home directory over the ssh connection. Now on the remote server, unzip the project zip file.

ubuntu@ubuntu:~$ unzip graphQL.zip

Clone Application From Github, Bitbucket or Gitlab

The second method to copy application code to the server is using git. Install git from the command line on the EC2 server.

ubuntu@ubuntu:~$ sudo apt install git

Check the git version to verify the installation.

ubuntu@ubuntu:~$ git --version

If it does not give the version of git, then git is not installed. Now clone the application from the github, gitlab, or bitbucket. Here we will clone the application code from the github.

ubuntu@ubuntu:~$ git clone ttps://github.com/contentful/the-example-app.nodejs

Starting the GraphQL Application

Now we have our graphQL application on the remote server. Go to the root directory of the graphQL application and install the required npm packages to run the graphQL application.

ubuntu@ubuntu:~$ cd graphQL
ubuntu@ubuntu:~$ sudo npm install

This command will analyze the package.json file in the project and install all the required npm packages. After installing the required packages, now we will start the graphQL application.

ubuntu@ubuntu:~$ node app.js

Running Application as Daemon

When we run the application using the standard method as described above, it runs in the foreground, and the application stops when you close the terminal window. We can run the application as a background process by appending the ampersand (&) sign to the command.

ubuntu@ubuntu:~$ node app.js &

The problem with this method is that when we modify our application code, the applied changes will not reflect automatically. We will have to restart the application every time we modify the code to apply the changes. In order to run the application in the background and to apply changes automatically, we will use an npm package named pm2. Install pm2 on the server.

ubuntu@ubuntu:~$ sudo npm install -g pm2

Start the graphQL application using pm2.

ubuntu@ubuntu:~$ pm2 start app.js --name “graphQL” --watch

The ‘–name’ flag will name the background process, and we can start and stop the application using the name. The ‘–watch’ flag will go on checking the application code to apply changes immediately. You can learn more about pm2 by visiting the following link

https://pm2.keymetrics.io/

Querying GraphQL API from Browser

We can configure our graphQL application to make graphQL queries from the browser manually. For this, we have to create a separate HTTP endpoint on which we will mount the graphQL API server. And this HTTP endpoint will be used to make manual queries. Following is the code to create the graphQL api server endpoint.

const express = require(‘express’);
const { graphqlHTTP } = require(‘express-graphql’);
const { buildSchema } = require(‘graphql’);

const graphQLSchema = buildSchema(`
    type Query{
    message: String
    }`
);

const func = {
    message: () =>
    {
        return ‘you are using graphql api server’;
    }
};

const server = express();
server.use(/graphql’, graphqlHTTP({
    schema: graphQLSchema,
    rootValue: func,
    graphiql: true
}));

server.listen(3000);

Now, after running the server, we can access the graphQL api server on the following route.

http://localhost:3000/graphql

Querying GraphQL API Using CLI

In the previous section, we made graphQL queries from the browser using graphiql. Now we are going to make graphQL queries using the command-line interface in ubuntu. From the command line, to make an HTTP POST request, we will use the curl module.

ubuntu@ubuntu:~$ curl -X POST -H "Content-Type: application/json" -d '{"query": "{ message }"}' http://localhost:3000/graphql

Querying GraphQL API Programmatically

In order to make graphQL query programmatically, we will use the ‘node-fetch’ module in node.js. Open node.js in the terminal.

ubuntu@ubuntu:~$ node

Now make the HTTP POST request to the server using the ‘node-fetch’ module.

GraphQL is an efficient query language, and it can decrease the response time of a query made to the database. The standard api calls to fetch data from the database involve many unuseful data in the response, and hence response time increases, which decreases the efficiency. The query made to the databases using GraphQL returns only the useful data and hence decreases the response time. In this article, we have deployed our graphQL application on an EC2 instance.

]]>
Install and Use Node.js on Ubuntu 20.04 https://linuxhint.com/install_use_node-js_ubuntu/ Sat, 26 Sep 2020 18:32:28 +0000 https://linuxhint.com/?p=69251 Node.js is a powerful JavaScript runtime. It’s a free and open-source cross-platform solution that’s primarily for server-side programming. It allows developers to have scalable backend functionality using JavaScript. Most of the time, it’s used to create back-end apps. However, it’s also popular for full-stack and front-end solutions.

In this guide, check out how to install and use Node.js on Ubuntu 20.04.

Node.js on Ubuntu

Node.js is quite popular for scaling backend functionalities. In the case of Ubuntu, there are multiple sources to grab Node.js. Various methods will install different versions of Node.js. You can also manually select which one to go for.

Use the method that suits your needs the best.

Install Node.js from Ubuntu repos

This is the default method of installing Node.js on Ubuntu. For most of the users, this will be more than enough. The only downside is, you may not get the latest version of Node.js.

The installation is super simple. Update the APT cache and install Node.js along with npm (Node Package Manager).

$ sudo apt update && sudo apt install nodejs npm -y

Let’s run a quick test to verify the installation.

$ nodejs --version

Install Node.js from NodeSource PPA

NodeSource is a dedicated PPA that offers multiple versions of Node.js. I recommend this method over other ones as it offers more control. For advanced users, it also allows deciding the exact version of Node.js to install. At the time of writing this article, NodeSource PPA hosts Node.js v10, v12, v13, and v14.

Here, I’ll be showcasing how to configure NodeSource PPA for Node.js v14. If you want to install a different version of Node.js, check out the NodeSource readme for proper instruction.

First, make sure that your system has curl installed.

$ sudo apt update && sudo apt install curl -y

Now, run the NodeSource installation script.

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

Voila! NodeSource PPA for Node.js v14 is successfully configured! Install Node.js.

$ sudo apt install nodejs -y

Verify the installation by checking the version of Node.js.

$ node -v

Install Node.js using nvm

It’s an interesting way of installing Node.js. The nvm (Node Version Manager) is a tool that allows installing and maintaining multiple versions of Node.js along with associated Node packages independently. Check out nvm at GitHub.

To install nvm, run either of the following commands. Either of them will download the nvm install script and run it.

$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

$ wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

Close and re-open the terminal. This will load nvm. Otherwise, you can manually reload the bashrc file.

$ source ~/.bashrc

To verify the installation, run the following command.

$ command -v nvm

It’s time to use nvm. First, check out the available versions of Node.js. This will print out a long list.

$ nvm list-remote

To install the desired version, use the following command. In this example, the command will install Node.js v14.9.0.

$ nvm install v14.9.0

Using nvm, it’s possible to install a release based on its aliases. For example, run this command to install the latest LTS version erbium.

$ nvm install lts/erbium

The following command will list all the installed Node.js versions.

$ nvm list

If there are multiple versions installed, nvm allows switching to a different one. First, check the current Node.js version.

$ node -v

Change the default Node.js to a different version.

$ node use <version>

Instead of using the version number, using the version alias also works.

$ node use <version_alias>

Test the change.

$ node -v

The following command will set the default version of Node.js.

$ nvm alias default <version>

Install Node.js from source

As mentioned earlier, Node.js is an open-source project. We can grab the source code and manually build and use Node.js. However, this approach is strongly recommended to follow if you intend to use Node.js for production purposes.

Before jumping into the process, it’s important to note about Python. Node.js supports both Python 2 and Python 3. Node.js will use whichever one is installed. If both Python 2 and Python 3 are installed, the later will be used. If only Python 2 is installed, Python 2 will be used.

First, install the build dependencies. Run the following command. For Python 3 users, the python3-distutils package is necessary.

$ sudo apt update && sudo apt install python python3-distutils g++ make

Now, download the source code. In this example, I’ll be compiling the Node.js v12.18.3 (includes npm 6.14.6). Download Node.js source code.

$ wget https://nodejs.org/dist/v12.18.3/node-v12.18.3.tar.gz

Extract the source code.

$ tar -xvf node-v12.18.3.tar.gz

The time has come to build Node.js. Run the configuration script.

$ ./configure

Start the compilation process. The “-j” is to run make in multithread mode. The “nproc” part is to tell the number of available CPU cores.

$ make -j$(nproc)

Install Node.js.

$ sudo make install

Let’s verify the installation. Check the Node.js and npm version.

$ node -v
$ npm -v

Using Node.js

Node.js comes with a ton of features and functionalities. It’s a runtime for JavaScript. It’s up to you to leverage JavaScript to get the most out of Node. Here, I’ll be showcasing the very basic ways of using Node.js.

First, grab a sample JavaScript. The following code was grabbed from W3Schools.

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

Run the JavaScript code using Node.js.

$ node demo.js

To get the output, access your computer from port 8080.

Final thought

Node.js is a powerful and popular solution. There are multiple approaches to install it on Ubuntu. Your circumstance will dictate which method suits you the best. While using the default Node.js from Ubuntu repo offers the simplest solution, NodeSource and nvm offers more flexibility.

As for using Node.js, there are tons of materials online that teaches how to take advantage of various Node features in your JavaScript codes. W3Schools is a good place to start your journey.

Happy computing!

]]>
How to Install Node.js and npm on Ubuntu 20.04 https://linuxhint.com/install_node-js_npm_ubuntu/ Sat, 26 Sep 2020 17:47:34 +0000 https://linuxhint.com/?p=69203 Node.js is a runtime environment that comes with all the requisites to properly execute JavaScript files on your system. It is built on Chrome’s V8 JavaScript engine and uses the non-blocking I/O model. Npm is a package of Node.js and is a collection of almost all open-source libraries on the internet.

This article shows you how to get Node.js up and running on your Ubuntu 20.04 system using a non-root user account with sudo privileges.

There are two installation methods that we will look at:

  • Installing Node.js from Ubuntu’s official repository
  • Installing Node.js with nvm

Method 1: Installing Node.js from Ubuntu’s Official Repository

Installing Node.js with an apt package manager from Ubuntu’s official repository is fairly straightforward. First, update your package listing before running the installation command by entering the following:

$ sudo apt update

$ sudo apt install nodejs

Verify the install by checking the version of Node.js you have downloaded:

$ nodejs -v

The process shown above should download the latest package available in Ubuntu’s software repository. To download a specific version, try out one of the other methods in this tutorial.

You can install npm just like we installed Node.js with the apt repository. Enter the following command to commence installation of npm:

$ sudo apt install npm

You have now installed npm and Node.js on your system. You can now start using node.js and the npm library to add functionalities to the software on your system.

Method 2: Using nvm to Install Node.js

If you want to download a specific version of Node, or if you just want more customizability in the installation, using nvm in the process can do this for you. Nvm stands for Node Version Manager and is a tool that lets you administer several side-by-side and active Node. js versions on your system.

First, copy the curl command from the readme file on the GitHub page for nvm:

$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

Paste it on the command terminal and run it to install the nvm. Then, run the following command to source your bash file.

$ source ~/.bashrc

To see what versions of Node are available to download, enter the following command:

$ nvm list-remote

Then, add whichever version you want to download in the following command syntax:

$ nvm install v(version number)

For example, to download v14.9.0, you would write the command as follows:

$ nvm install v14.9.0

You have now successfully downloaded and installed Node.js v14.9.0 onto your system. You can download multiple different versions with nvm without the versions interrupting each other. You can even download and install long-term support versions of Node with nvm, such as Erbium or Dubnium. For example, the following command installs the latest Erbium version:

$ nvm install lts/erbium

You can see all the versions of Node installed on your system by entering the following:

$ nvm list

Use the following command to enter a different version of Node:

$ nvm use v14.9.0

Nvm is a great tool to use because it brings together many options for efficient management of the Node.js software.

Wrapping Up

This tutorial looked at two different ways to install Node.js on an Ubuntu 20.04 server: by using nvm, and by directly requesting the program from the standard Ubuntu repository. If you are looking to install the latest version as quickly as possible, you should go with the first method. Otherwise, if you want more flexibility with your install, you can choose either of the two methods.

Check out Nodeproject’s official homepage to learn more about how to use Node on your Ubuntu 20.04 system. ]]> Connecting MySQL with NodeJS https://linuxhint.com/connect_mysql_nodejs/ Sun, 12 Apr 2020 06:22:26 +0000 https://linuxhint.com/?p=57855 MySQL server is a very popular database server and it is supported by mostly used programming languages, such as PHP, Python, Perl, Java, C#, etc. It is an open-source application, so anyone can download this application for storing, retrieving, updating and deleting data by using database queries. You will require the server and client packages to be installed in your system to perform different types of database operations in the database server. MySQL server is now becoming popular for Node developers also. Node developers start using MySQL server with MongoDB for some special features of the MySQL server. How you can make a connection with MySQL server using the node-mysql client is shown in this tutorial.

Prerequisite:

Before starting this tutorial you have to confirm that MySQL server and client packages are installed and working properly in your system. If you install the MySQL server for the first time then the password of root user is empty by default. But you have to set the password for the root user to make a connection with MySQL server using the node-mysql client. You can check this tutorial to know how to change the root password of the MySQL server.

Run the following commands to work as a root user and connect with MySQL server by using MySQL client.

$ sudo -i
$ mysql -u root -p

Enter the root password and run the following SQL commands to create a new database, create a table on that database and insert some records in that table.

The following command will create a database named mydb.

The following command to select the database for doing database operations.

use mydb;

The following command will create a table named book in the database mydb.

CREATE TABLE book (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50) NOT NULL,
author VARCHAR(50) NOT NULL,
price int(5));

The following command will insert four records into book table.

INSERT INTO book values
(NULL,'Learning PHP and MySQL', 'Robin Nixon', 45),
(NULL,'Learning JQuery', 'Jonathan', 35),
(NULL,'Angular in Action', 'Jeremy', 50),
(NULL,'Mastering Laravel', 'Christopher', 55);

Install mysql client for nodejs:

Run the following command to check nodejs is installed in the system before running the command of installing mysql client of nodejs. It will show the installed version of nodejs.

$ node -v

If it not installed then you have to install it by running the following command.

$ sudo apt-get install nodejs

You will require another package named npm to be installed in the system to install mysql client for nodejs. If it is not installed before run the following command to install npm.

$ sudo apt-get install npm

Now, run the following command to update the system.

$ sudo apt-get update

The following command will install mysql module for nodejs that will work as mysql client.

$ npm install mysql

Simple MySQL connection using NodeJS:

Create a JS file named connection1.js with the following script to make a connection with the previously created database named mydb and read data from book table. mysql module is imported and used for creating a simple connection with the MySQL server. Next, a query will be executed to read all records from book table, if the database is connected properly. If the query executed properly then all records of book table will be printed in the terminal and the database connection will be closed.

connection1.js

// Import mysql module
let mysql = require('mysql');

// Setup database connection parameter
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb'
});

// Connect with the database
connection.connect(function(e) {
if (e) {

// Show error messaage on failure
return console.error('error: ' + e.message);
}

// Show success message if connected
console.log('\nConnected to the MySQL server...\n');
});

// Set the query message
$query = 'SELECT * from book';

// Execute the database query
connection.query($query, function(e, rows) {
if(e){

// Show the error message
console.log("Error ocurred in executing the query.");
return;
}
/* Display the formatted data retrieved from 'book' table
using for loop */

console.log("The records of book table:\n");
console.log("Title\t\t\t\t Author\t\tprice\n");
for(let row of rows) {
  console.log(row['title'],"\t\t",row['author'],"\t","$",row['price']);
}
});

// Close the database connection
connection.end(function(){
console.log('\nConnection closed.\n');
});

Output:

Run the following command to execute the script.

$ node connection1.js

The following output will appear after running the script.

Pooled MySQL connection using NodeJS:

Making a simple MySQL connection with NodeJS using mysql module is shown in the previous example. But many users can connect with the database server at a time through the application when the application is created with MySQL database for production purposes. You will require the express module to handle concurrent database users and support multiple database connections.

Run the following command to install the express module.

$ npm install express

Create a JS file named connection2.js with the following script. If you connect with MySQL with the following script then 10 concurrent users will be able to make a connection with the database server and retrieve data from the table based on the query. It will make a connection at the port 5000.

connection2.js

// Import mysql module
var mysql = require('mysql');

// Import express module
var express = require("express");

// Define object of express module
var app = express();

// Make database connection to handle 10 concurrent users
var pool = mysql.createPool({
connectionLimit :10,
host : 'localhost',
user : 'root',
password : '1234',
database : 'mydb',
debug : true
});

/* Make pooled connection with a database and read specific records from a table of that
 database */

function handle_database(request,response) {

// Make connection
pool.getConnection(function(e,connection){
if (e) {

  //Send error message for unsuccessful connection and terminate
  response.json({"code" : 300, "status" : "Database connection errror"});
  return;
}

// Display success message in the terminal
console.log('Database connected');

// Read particular records from book table
connection.query("SELECT * from book where title like '%PHP%' or title like
'%Laravel%'"
,function(e,rows){ connection.release();
if(!e) {

  // Return the resultset of the query if it is successfully executed
  response.json(rows);
}
});

// Check the connection error occurs or not
connection.on('error', function(e) {
response.json({"code" : 300, "status" : "Database connection errror"});
return;
});
});
}

// Call the function for making connections
app.get("/",function(request,response){-
handle_database(request,response);
});

// Listen the connection request on port 5000
app.listen(5000);

Output:

Run the script from the terminal like the previous example. It will wait for the connection request after running the script.

$ node connection2.js

Now, open any browser and go to the following URL to send a connection request.

http://localhost:5000

The following output will appear as a response after executing the query.

If you open the terminal now then you will see the following output.

Ten connection requests can be sent at a time from 10 browsers in the way mentioned above.

Conclusion:

The most simple ways to work with MySQL and NodeJS are shown by two examples in this tutorial. If you are a new Node developer and want to work with MySQL database then I hope you will be able to do your task after reading this tutorial.

]]>
Simple NodeJS Application https://linuxhint.com/simple_nodejs_application/ Sat, 21 Mar 2020 16:57:16 +0000 https://linuxhint.com/?p=56935 In the last couple of years, the world has undergone some fascinating technological changes. Each day, something new is developed that offers an improvement over its predecessor and gives us access to a whole new dimension. One certain region that has seen a significant improvement in its features and popularity is the web development sector, particularly NodeJS, which has become many developers’ first choice for back-end development.

What actually is NodeJS?

NodeJS is an open-source JavaScript platform used for developing and executing back-end services called APIs (Advanced Programming Interfaces). These are the services that power up the client applications such as web apps that run on the browser and mobile applications. NodeJS is important because these client applications are just a surface for users to see and interact with. In addition to this, they need to talk to some service on the server or in the cloud for the storage of data, sending emails or pushing notifications. This is where NodeJS comes into the picture which allows users to create server-based applications in JavaScript and produce real time back-end services that can be used to power up client applications.

Being highly scalable and superfast, NodeJS is a great choice for development and hence today we’ll be looking at how to make a simple NodeJS application.

Step 1: Installing NodeJS

Before moving on the development phase, let us first see how to install NodeJS on our Linux based desktops. There are actually multiple ways to install NodeJS on a Linux based computer. We, however, will only be looking at two methods of installing NodeJS.

Step 1(a): Installing NodeJS using NVM

In this method, we will be using the Node Version Manager (NVM) to install NodeJS. A huge benefit of using this is that there are no permission issues for using NodeJS.

First of all, we have to install nvm which can be done by the following command:

$ wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.1/install.sh | bash

This command adds nvm to your path profile and extracts all the nvm data in the directory ~/. nvm

To check whether nvm has been installed correctly, restart the terminal and run:

$ command -v nvm

If you see nvm as the output, then it has been successfully installed.

Now we’ll be installing NodeJS and npm which is basically an ecosystem of NodeJS libraries. To do this, simply run the following command that will install the most recent version of NodeJS:

$ nvm install node

You can also install any specific version of NodeJS that you want to install. For this tutorial, we’ll be installing the version 12 of NodeJS.

$ nvm install v12.16.1

Once installed, you can check your NodeJS and npm installed versions by running the following commands:

$ node -v
$ npm -v

Step 1(b): Installing NodeJS using Ubuntu official repository

One huge advantage of installing NodeJS in this way is that Ubuntu has a stable version of NodeJS in its official repository.

First of all, the following command will be run to update our system’s apt cache and packages to the latest versions so that no issues arise during installation:

$ sudo apt-get update

Next, we will be installing NodeJS with the following command:

$ sudo apt install nodejs

Once installed, you can check your NodeJS installed version by running the following command:

$ node -v

In this method, we also have to install npm, the ecosystem of NodeJS libraries. This can be done by inputting the following command into the terminal:

$ sudo apt install npm

Similarly, you can check your npm installed version by running the following command:

$ npm -v

Step 2: Coding a NodeJS Application

For this tutorial, we’ll be creating a simple HTTP Server which will listen to the client on port number 8080 and output Hello World as a response to the client. The following is the complete code:

let http = require('http')
server = http.createServer(function(request, response) {
    response.write('Hello World')
    response.end()
})

server.listen(8080)
console.log ("Server Running")

Let us now look at each line of code to understand what is actually happening here.

Code Explanation:

In Node JS, there are some built in modules available. These are functions that have already been defined in NodeJS and provide certain functionality in our applications. These modules can be imported using the require keyword.

let http = require('http')

In the first line of our code, we are importing the HTTP built in module of NodeJS. The HTTP module is used here so that we can create a server in our application that can listen for HTTP requests on a given port.

server = http.createServer(function(request, response)

Over here, we use a method of the HTTP module called createServer which, as the name says, creates a server instance. In this, we pass a function through here which takes up two parameters – a request object and a response object. Now whenever a request is made to our server, this function will be called. The response object comes loaded with details about the request that has been made and the response object is something that we can use to send a response back to the client.

response.write('Hello World')
response.end()

Over here, response.write is used to write a response to the client. This is how things can be printed on the browser. In this case, this will allow us to print Hello World on the browser. The response.end() lets the browser know that the request has ended and sends the response to the browser.

server.listen(8080)
console.log ("Server Running")

The server.listen function is used here by our server to listen to the client on port number 8080. It is important to note that any port that is available can be used here. The last line console.log is used to print anything on the terminal. In this case, we are printing Server Running so that we know the server has started.

Step 3: Running and Testing our NodeJS Application

Now that we have our code written and understand what is happening in it, let us now run it and test whether it is working or not. To do this, open the directory, where you have saved your file containing the above NodeJS code and along with this, also open the terminal. In order to run a NodeJS file, simply type in the following command in the terminal:

$ node filename.js

filename here refers to the name of your file. In my case, I’ve stored my code in a file called sample.js. See below:

$ node sample.js

Now our server seems to be running. Let us now check to see if our response has been sent to the client. To do this, open your browser and enter localhost: port. In my case, I’ll be running the command: localhost:8080. See the image below for better understanding:

We can clearly see our output Hello World displayed on the page. Voila, we were successful in creating a simple NodeJS Server.

Why use NodeJS over its Alternatives?

In today’s world, JavaScript has completely changed the face of web development. This has thus led to NodeJS becoming a popular choice for back-end development. Along with using JavaScript as its core, NodeJS is highly fast, extremely flexible and great for prototyping and agile development. Moreover, using NPM (Node Package Manager) as its ecosystem which is the largest ecosystem available for open-source libraries, it grants multiple tools and modules to developers which further increases its demand. All these reasons make it a great choice for web development.

]]>
Installing Node.js on CentOS 8 https://linuxhint.com/install_nodejs_centos8/ Sun, 10 Nov 2019 09:39:16 +0000 https://linuxhint.com/?p=49827 In this article, I am going to show you how to install Node.js on CentOS 8. So, let’s get started.

Installing Node.js using Package Manager:

Node.js is available in the official package repository of CentOS 8. So, you can easily install it on CentOS 8 using DNF or YUM package manager.

First, update the CentOS 8 package repository cache with the following command:

$ sudo dnf makecache

The CentOS 8 package repository cache should be updated.

Now, to install Node.js and NPM package manager on CentOS 8 from the official package repository of CentOS 8, run the following command:

$ sudo dnf install nodejs npm

Now, to confirm the installation, press Y and then press <Enter>.

Node.js and NPM should be installed.

Once Node.js and NPM is installed, check whether Node.js is working correctly as follows:

$ node --version

As you can see, Node.js v10.16.3 is installed.

Also, check whether NPM is working correctly as follows:

$ npm --version

As you can see, NPM v6.9.0 is installed.

The same way, check whether NPX is working as follows:

$ npx --version

As you can see, NPX v6.9.0 is installed.

Installing Node.js Manually from the Official Website of Node.js:

The version of Node.js and NPM in the official package repository of CentOS 8 is old.

At the time of this writing, the latest LTS version of Node.js is v12.13.0 and the latest version of Node.js is v13.0.1.

If you want to install the latest LTS version of Node.js or the latest version of Node.js on CentOS 8, you will have to download Node.js from the official website of Node.js and manually install it on CentOS 8.

First, visit the official website of Node.js. Once the page loads, click on the LTS version button if you want to install the latest LTS version of Node.js. Otherwise, click on the Current version button if you want to try out the latest version of Node.js.

Your browser should prompt you to save the file. Select, Save File and click on OK.

Your browser should start downloading the Node.js archive. It may take a while to complete.

If you’re using a headless version of CentOS 8, then visit the official website of Node.js from any browser. Once the page loads, right click (right mouse click) on the download button and copy the download link.

Now, SSH into your CentOS 8 machine and use wget to download the Node.js archive file using the link that you’ve copied earlier as follows:

$ wget https://nodejs.org/dist/v12.13.0/node-v12.13.0-linux-x64.tar.xz

Once Node.js archive file is downloaded, navigate to the directory where the archive file is downloaded (usually ~/Downloads) as follows:

$ cd ~/Downloads

The Node.js archive file should be there.

$ ls -lh

Now, you have to extract the Node.js archive file. I will extract it in the /opt directory. If you want, you can extract it to some other directory. Just replace /opt with the directory path where you want to extract the Node.js archive file.

To extract the Node.js archive file in the /opt directory, run the following command:

$ sudo tar xvJf node-v12.13.0-linux-x64.tar.xz -C /opt

Node.js archive file should be extracted in the /opt directory.

Once the Node.js archive file is extracted, a new directory (node-v12.13.0-linux-x64 in my case) should be created in the directory where you extracted it.

$ ls /opt

Now, you have to add the path of Node.js to the PATH environment variable in order to access Node.js, NPM and NPX binaries easily.

You can create a shell script in the /etc/profile.d/ directory which will automatically update the PATH environment variable every time your CentOS 8 machine boots.

To create a new shell script /etc/profile.d/node-v12.sh, run the following command:

$ sudo vi /etc/profile.d/node-v12.sh

Now, press I to switch to the Vi INSERT mode and type in the following lines of codes in the node-v12.sh file.

export NODE_VERSION=v12.13.0
export NODE_DISTRO=linux-x64
export NODE_HOME="/opt/node-${NODE_VERSION}-${NODE_DISTRO}"
export PATH="$PATH:${NODE_HOME}/bin"

NOTE: By the time you read this article, new versions of Node.js may be released. So, make sure to change NODE_VERSION from v12.13.0 to the version of Node.js you’re trying to install.

If you’re extracting the Node.js archive file to some other directory than /opt, then change /opt to the directory you’re extracting the Node.js archive file.

The final shell script file should look as follows.

To save the file node-v12.sh, press <Esc> to switch to Vi COMMAND mode, type in :wq! and then press <Enter>.

Now, reboot your CentOS 8 machine with the following command:

$ sudo reboot

Once your CentOS 8 machine boots, verify whether the shell script set all the Node.js environment variables correctly with the following command:

$ env | grep NODE

As you can see, the Node.js environment variables are correctly set.

Now, check whether the PATH environment variable is updated correctly with the following command:

$ echo $PATH

As you can see, the Node.js binary path is in the PATH environment variable. Great!

Now, check whether Node.js is working correctly with the following command:

$ node --version

As you can see, the version of Node.js installed is v12.13.0. So, it’s working

Also, check whether NPM is working correctly with the following command:

$ npm --version

As you can see, the version of NPM installed is 6.12.0. It’s working as well.

Lastly, check whether NPX is working correctly with the following command:

$ npx --version

As you can see, the version of NPX installed is 6.12.0. It’s also working.

So, that’s how you install Node.js on CentOS 8. Thanks for reading this article.

]]>
Installing Node.js on Debian 10 https://linuxhint.com/install_nodejs_debian_10/ Tue, 30 Jul 2019 11:08:42 +0000 https://linuxhint.com/?p=44495 Node.js is a server side JavaScript runtime. Node.js is open source and cross platform. Node.js runs on Linux, Windows and macOS. It is mainly used to develop software APIs and networking applications.  In this article, I am going to show you how to install Node.js on Debian 10 and how to run a simple Node.js program on Debian 10. So, let’s get started.

Installing Node.js 10 LTS:

Node.js 10.x is the latest LTS version of Node.js at the time of this writing. Luckily, it is available in the official package repository of Debian 10. So, you can easily install it using the APT package manager on your Debian 10 machine.

First, update the APT package repository cache with the following command:

$ sudo apt update

The APT package repository cache should be updated.

Now, install Node.js from the official Debian 10 package repository with the following command:

$ sudo apt install nodejs

Now, to confirm the installation, press Y and then press <Enter>.

The APT package manager will download and install all the required packages.

Node.js 10.x should be installed.

As you can see, the Node.js version installed from the official package repository is v10.15.2.

$ node --version

Node.js has its own package repository to help you out in your work. Luckily, Debian 10 packages a lot of common and stable Node.js packages. You can easily download them from the official package repository of Debian 10. The Node.js Debian 10 package names start with node-*

For example, I searched for express.js Node.js package on the official Debian 10 package repository. As you can see, the package exists. The express-generator package exists as well. The package names are node-express and node-express-generator in Debian 10. You can easily use the APT package manager to install these packages and use them in Node.js 10.

I also searched for the Node.js package bluebird. It exists as well.

If you rather want to install Node.js packages using NPM, then you have to install NPM from the official package repository of Debian 10 with the following command:

$ sudo apt install npm

Now, confirm the installation by press Y followed by <Enter>.

The APT package manager will download and install all the required packages.

At this point, NPM should be installed.

As you can see, the NPM version installed from the Debian 10 package repository is 5.8.0.

The Node.js packages that are in the Debian 10 package repository are very stable and well tested. You can use them if you want.

Installing Node.js 12:

At the time of this writing, the latest version of Node.js is version 12.x. But, it is not available in the official package repository of Debian 10. You have to install it manually from the official package repository of Node.js.

Before you install Node.js 12.x, you have to install some dependency packages from the Debian 10 package repository.

First, update the APT package repository cache with the following command:

$ sudo apt update

The APT package repository should be updated.

Now, install the dependency packages build-essential and curl with the following command:

$ sudo apt install build-essential curl

Now, press Y and then press <Enter> to confirm the installation.

The dependency packages should be installed.

Now, add the official Node.js 12.x package repository with the following command:

$ curl -sL https://deb.nodesource.com/setup_12.x</a> | sudo bash -

The Node.js 12.x package repository should be added and the APT package repository cache should be updated.

Now, install Node.js 12.x with the following command:

$ sudo apt install nodejs

The APT package manager should download and install all the required packages.

Node.js 12.x should be installed.

As you can see, I am running Node.js 12.7.0.

$ node --version

Node.js installed from the official Node.js package repository installs NPM by default. As you can see, I am running NPM 6.10.0.

Writing Your First Node.js Program:

In this section, I am going to show you how to write your first Node.js program.

First, create a project directory (let’s call it ~/hello-node) as follows:

$ mkdir ~/hello-node

Now, navigate to the project directory ~/hello-node as follows:

$ cd ~/hello-node

Now, create a new file welcome.js in the project directory ~/hello-node and type in the following lines of code in the welcome.js file.

let http = require('http');
const PORT = 8080;
 
let server = http.createServer((req, res, next) => {
res.writeHead(200, {
'Content-Type': 'text/html'
});
 
res.end('<h1>Welcome to LinuxHint!</h1>');
});
 
server.listen(PORT, () => {
console.log("Visit http://localhost:" + PORT + " from your web browser.");
});

The final welcome.js program looks as follows:

Now, to run the Node.js program welcome.js, run the following command:

$ node welcome.js

As you can see, the welcome.js program is running.

Now, visit http://localhost:8080 from your web browser and you should see a welcome message as shown in the screenshot below.

So, that’s how you install Node.js on Debian 10 and run your first Node.js program. Thanks for reading this article.

]]>
Setting Up Node.js Development Environment https://linuxhint.com/nodejs_environment_docker/ Sun, 02 Jun 2019 09:13:55 +0000 https://linuxhint.com/?p=41313 You can always install Node.js on your computer and run Node.js applications there. But, there are situations where you will want to use Docker to do your Node.js development.

For example, let’s say, you don’t want to install Node.js on your computer and still want to develop Node.js applications or test an existing one. In that case, you can simply use a Node.js Docker container.

Another example is where you need to test your Node.js application on different versions of Node.js. In that case, you can use different Node.js Docker containers with different version of Node.js installed to test your application.

In this article, I will show you how to set up Node.js development environment using Docker. So, let’s get started.

Setting Up Project Directory:

In this section, I will clone one of my Node.js API app from GitHub to my ~/Projects/ directory just for testing Docker Node.js development environment I am about to show you how to setup. This is not required. You can always use your own Node.js app if you want.

First, I am going to navigate to my ~/Projects/ directory as follows:

$ cd ~/Projects/

Now, I am going to clone my shovon8/angular-hero-api GitHub repository as follows:

$ git clone https://github.com/shovon8/angular-hero-api

The project files will be in the angular-hero-api/ directory as you can see in the screenshot below.

Node.js Docker Images:

There are official container images for different version of Node.js built on top of different Linux distribution on DockerHub. Visit https://hub.docker.com/_/node/ from your favorite browser to find the Node.js image you need. As you can see, the tag name for all the Node.js images are listed in the DockerHub page of Node.js. You can either use Debian Jessie/Stretch, Alpine, ChakraCore Linux distribution based images for different versions of Node.js.

Usually, you don’t have to know much to use a Node.js Docker image. If you want to use Node.js version 12, then all you have to do is write node:12 when you make a container. For Node.js 10, it is node:10. For Node.js 8, it is node:8. It’s that simple.

Configuring the Node.js Development Environment:

In this section, I am going to configure Linux command aliases for my Node.js API app. That way, I can easily use any version of Node.js I want to run my app.

In each of my Node.js project directory, I will create a new file source. In that file, I will keep the command aliases like node12 for Node.js 12 runtime, node10 for Node.js 10 runtime, node8 for Node.js 8 runtime running on Docker. You can reuse the same source file with slight modification on your other Node.js projects as well.

First, navigate to your project directory as follows:

$ cd angular-hero-api/

Now, create a source file with the following command:

$ nano source

Now, type in the following lines in the source file.

alias node12='docker run -it --rm --name hero-api -p 4242:4242 -v
"$PWD:/usr/src/app" -w /usr/src/app node:12'


alias node10='docker run -it --rm --name hero-api -p 4242:4242 -v
 "$PWD:/usr/src/app" -w /usr/src/app node:10'


alias node8='docker run -it --rm --name hero-api -p 4242:4242 -v
 "$PWD:/usr/src/app" -w /usr/src/app node:8'

Here, -it means, run the container in interactive mode.

–rm means remove the container automatically when it’s no longer needed.

–name hero-api defines a name for the container.

-p 4242:4242 means the container port 4242 is forwarded to the destination port (on your computer) 4242. The format of this option is -p destination:source. Remember, the first port before the colon (:) is the destination port. If you want to access your application on some other port than 4242 on your computer, then you have to change the destination port. If your applications run on some other port than 4242. Then you have to change the source port.

NOTE: As I will only be using one of the containers at any one time, the name and destination port can be the same. If you wish to run or test your Node.js application on multiple Node.js version at the same time, then make sure the name and destination port is different for each of the containers in the source file.

Once you’re done, save the file by pressing <Ctrl> + x followed by y and <Enter>.

Now, enable the aliases with the following command:

$ source source

Now, you can run any version of node runtime whenever you need with node12, node10, node8 commands as you can see in the screenshot below.

Running Hero API Node.js App:

Now, let’s see how to run the angular-hero-api app from my GitHub repository with this setup. I am going to use Node.js 12 runtime first, then go for Node.js 10 and Node.js 8 runtime to show you that it works in each of the versions.

The API app does not have any node modules installed. So, you have to install all the required node modules with npm install command as follows:

$ node12 npm install

The node modules are installed as you can see in the screenshot below.

Now, run the Node.js API app as follows:

$ node12 npm run test

As you can see, the API server is running on port 4242 on the container. I also forwarded the port to 4242 on my computer. So, I should be able to access it on port 4242.

Yes, I can access it. It’s working as expected.

Now, stop the container by pressing <Ctrl> + c.

Let’s try to run the API app with Node.js version 10.

$ node10 npm run test

As you can see, it’s running.

It works for Node.js 10 as well.

Finally, let’s try for Node.js version 8.

$ node8 npm run test

The API app is running on Node.js 8 runtime as well.

Perfect! It works correctly.

So, that’s how you set up Node.js development environment using Docker. Thanks for reading this article.

]]>
Practical introduction to Nodejs: Installing and learning NodeJS on Debian and Ubuntu https://linuxhint.com/introduction_nodejs_debian/ Mon, 13 May 2019 07:53:48 +0000 https://linuxhint.com/?p=40009 PHP is the world’s most used programming language for websites despite experienced developers admit the superiority of other languages like NodeJS or Ruby on rails for web applications.

Node JS is based on JavaScript, it is faster than PHP and has very better performance with interactive applications. The language Nodejs is easy to learn and even more if you already know a little of JavaScript.

In this tutorial you’ll get explained how to install Node JS on Debian and Ubuntu. If you don’t have previous knowledge on JavaScript basics avoid reading the section of this article called “NodeSchool: learn Node JS easy”, when reaching that section omit it and go directly to the next one called “Javascript on NodeSchool”.

To install NodeJS run:

apt install nodejs

You can run nodejs -v to make sure you installed it properly.

Node JS uses npm as default package manager. Type npm to see if you have it installed:

If you get an error instead of npm’s man page run:

apt install npm

Let’s check the npm packages manager installing MongoDB, first of all, create a directory dedicated to NodeJS (create it by running mkdir< DIRECTORYNAME>). Before using npm we need to start a new project and setup a package.json, a package.json must contain it’s name, description, version, link, keywords, author and license. To start a new project run:

npm init

Fill the required fields and end the installation, then type:

npm install mongodb

In my case it was previously installed so it only updated a package. As you can see the basic syntax is easy as apt.

NodeSchool: learn Node JS easy:

NodeSchool is a great multilingual website to learn Nodejs development. If you don’t know JavaScript you may want to avoid the next steps and go directly to the end of the article to see the way to get started with JavaScript before trying Nodejs.

To get started with the Nodejs’ tutorial install learnyounode by running:

npm install -g learnyounode

The parameter -g instructs a global installation, a Nodejs global installation will install the package as global module, otherwise the installation would be only for the current project.

After installing learnyounode run it by typing in the terminal:

learnyounode

This menu is the workshopper menu, you can start by hitting ENTER at HELLO WORLD and follow the instructions to get started with Nodejs.

Javascript on NodeSchool

At NodeSchool we can also learn JavaScript and HTML. To get started with NodeJS is better to have previous knowledge on JavaScript, after installing nmp install the workshopper for JavaScript by typing:

npm install -g javascripting

Note: The parameter -g instructs a global installation, a Nodejs global installation will install the package as global module, otherwise the installation would be only for the current project.

Then run

javascripting

The JavaScripting menu will guide you through the course to get started with JavaScript, press ENTER on the introduction to get started and follow the instructions.

I hope you found helpful this article to get started with Nodejs, a very powerful language for web programming. Keep following LinuxHint for more tips and updates on Linux.

]]>
NodeJS with Redis https://linuxhint.com/nodejs_redis/ Mon, 22 Oct 2018 08:26:17 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=31304 Redis is widely used as a caching server. At times, Redis is used as a database as well. It stores the data in a computer’s memory (RAM) directly. The advantage is that it can access the data very fast. The disadvantage is that the data it stores is temporary. If you reboot your computer, then all the data will be gone.

In this article, I will show you how to use Redis with Node.js. I will be using Node.js 10.x on Debian 9 Stretch in this article. But any modern version of Node.js should work. So, let’s get started. To get started you must have the following requirements:

  • js and NPM installed on your computer.
  • Redis installed on your computer.

You should be able to find articles on installing Node.js and NPM on your desired Linux distribution on LinuxHint.com.  I’ve written a dedicated article on installing Redis on Ubuntu/Debian.

Starting Redis:

You can check whether redis service is running with the following command:

$ sudo systemctl status redis

As you can see, redis service is running.

If redis service is not running in your case, start it with the following command:

$ sudo systemctl start redis

Initializing the Project Directory:

First, create a project directory (let’s call it node-redis) with the following command:

$ mkdir ~/node-redis

Now navigate to the project directory ~/node-redis

$ cd ~/node-redis

Now create a package.json file:

$ npm init -y

Installing Redis Node.js Module:

There are many Redis clients for Node.js. The official website of Redis recommends redis. You can easily install the redis Node.js module using NPM (Node Package Manager).

To install redis Node.js module, run the following NPM command:

$ npm install redis --save

redis Node.js module should be installed.

Connecting to Redis using Node.js:

In this section, I am going to show you how to connect to Redis data store using Node.js.

First, create a new file connect.js in your project directory and type in the following commands in it:

Here, line 1 imports the redis module.

Line 2 creates a Redis client. As I am running Redis on the same computer as the Node.js programs are running, I didn’t have to specify the hostname or IP address and port where the Redis server is running. If you’re running Redis server on a different computer or server, then you will have to specify it here.

For example, let’s say, your Redis server is running on port 6379 on a computer which has the IP address 192.168.10.87, then you would write line 2 as:

let client = redis.createClient(6379, '192.168.10.87');

Line 4-6 is used to print a message to the console if we can connect to the Redis server.

Line 9-10 is used to print a message to the console if we are unable to connect to the Redis server.

Now, run the connect.js Node.js script as follows:

$ node connect.js

As you can see, I am connected to the Redis server.

Storing Data in Redis Using Node.js:

In this section, I will show you how to store data (key-value pairs) in Redis data store with Node.js

First, create set1.js file in your project directory and type in the following lines in it:

Here, line 1 and 2 are the same as in connect.js.

On line 4, I set the callback function of the connect event to storeData. So, when our Redis client is connected to the Redis server, the function storeData is called.

On line 6-10, the callback function storeData is defined.

On line 7 and 8, I used set(key, value) method of RedisClient object to set the key name and country to value Mary Smith and USA respectively.

Now, run set1.js as follows:

$ node set1.js

As you can see, the key-value pairs are set.

Retrieving Data from Redis Using Node.js

In this section, I will show you how to retrieve data from Redis data store using Node.js.

First, create a new file get1.js in your project directory and type in the following lines:

Here, on line 4, getData function is set as a callback function for the connect event of RedisClient.

On line 6-9, the getData function is defined.

On line 7, I called the get(key, callback) method of RedisClient object. name here is the key of the value you want to retrieve. get() method calls the printValue callback function before it finishes running.

On line 11-18, the error first style callback function printValue() is defined. It accepts 2 arguments, error and result. If any error occurs, then it’s printed on the console and the function exits. If there’s no error, then the value for the certain key is printed on the console.

On line 8, the same thing happens.

Now, run get1.js as follows:

$ node get1.js

As you can see, the values for the keys name and country is retrieved from the Redis data store.

Storing Objects in Redis with Node.js:

You can store JavaScript objects in Redis data store.

First, create a new file set2.js in your project directory and type in the following lines in it.

Here, everything is the same as in set1.js file that I already explained earlier. The only difference is, I used client.hmset(key, object) method of RedisClient object in setData() callback function.

In line 7-10, I used client.hmset() method to store a JavaScript object in the Redis data store against the key C011.

Now run set2.js Node.js script as follows:

$ node set2.js

As you can see, the object is stored.

Retrieving Objects from Redis with Node.js:

In this section, I am going to show you how to retrieve objects from Redis data store.

Fist, create a new file get2.js in your project directory and type in the following lines in it.

Here, everything is the same as in get1.js script I explained earlier.

You can retrieve a JavaScript object very easily with client.hgetall(key, callback) method of RedisClient as in line 7-9.

Now run get2.js Node.js script as follows:

$ node get2.js

As you can see, the JavaScript object is retrieved from the Redis data store.

I showed you how to setup Redis with Node.js in this article. Now you should be able to read the redis Node.js module documentation at http://redis.js.org and learn more about it. Thanks for reading this article. ]]> Node.js Send E-Mail with Attachment https://linuxhint.com/nodejs_send_email_with_attachment/ Fri, 05 Oct 2018 04:18:49 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=30965 Node.js is the server side JavaScript engine that is loved by web developers and system administrators all over the world. Node.js has a rich set of modules that you can install using Node Package Manager (NPM) and use to do almost any task.

There are many Node.js modules for sending E-Mails using Node.js such as Nodemailer, emailjs, express-mailer etc.

In this article, I will show you how to send E-Mail and also how to send E-Mail with attachment with Nodemailer Node.js module. Let’s get started.

Requirements:

To follow this article, you should have:

  • Basic understanding of Node.js and JavaScript.
  • js 6.x or later installed on your computer.
  • NPM installed on your computer.
  • An E-Mail account such as GMail.
  • A Text Editor for writing Node.js codes.

You should be able to find dedicated articles on each of these topics on linuxhint.com. Be sure to check them for more information.

Creating Project Directory:

It’s always best to create a new directory for every Node.js app you write. Because by default, Node.js modules are installed in node_modules/ directory inside your current working directory. That way, modules are separate for each app you write and you can use different version of the same module in different app. This is a lot flexible than installing modules globally.

Create a project directory (let’s call it node-mail) with the following command:

$ mkdir node-mail

Now navigate to the project directory with the following command:

$ cd node-mail

Now create a package.json file with the following command:

$ npm init -y

As you can see, a basic package.json file is created.

Installing Nodemailer:

In this section, I am going to show you how to install Nodemailer Node.js module using NPM.

First, make sure Node.js is installed and working correctly with the following command:

$ node --version

As you can see, Node.js 10.11.0 is installed and working correctly in my computer. The version on your computer may be different. It’s alright but it should be version 6.x or later. Otherwise Nodemailer won’t work.

Now, make sure NPM is installed and working correctly with the following command:

$ npm ---version

As you can see, NPM 6.4.1 is installed and working correctly in my computer. The version on your computer may be different. It’s alright.

You need internet connectivity in order to install Nodemailer using NPM. So make sure you’re connected to the internet.

Now, install Nodemailer Node.js module using NPM with the following command:

$ npm install nodemailer --save

Nodemailer is installed.

Sending E-Mail with Nodemailer:

In this section, I will show you how to send E-Mail from your gmail account with Nodemailer.

First, create a new file (let’s call it sendmail.js) in your project directory with the following command:

$ touch sendmail.js

Now type in the following lines of code in sendmail.js file and save it.

Here, on line 1, I imported Nodemailer.

On line 3, I set my email to myEmail variable. This is the email from which I will send an email to other email accounts. Make sure you change it to your email address.

On line 5-11, a transport object is created. It is required to send an email using Nodemailer. The purpose of the transport object is to verify the sender information. You only need to do it once. Once the sender information is verified, a transport object should be created.

On line 6, I set service to gmail as I am using a GMail account to send emails. The supported services are DynectEmail, Gmail, hot.ee, Hotmail, iCloud, mail.ee, Mail.Ru, Mailgun, Mailjet, Mandrill, Postmark, QQ, QQex, SendGrid, SES, Yahoo, yandex, Zoho. The service name is case insensitive. So you can put gmail or GMAIL or Gmail there. It’s all the same.  Make sure you set the correct service name.

NOTE: You can use your own email server as well. To do that, you have to create a custom Nodemailer Transport object. To learn more about it, visit the official documentation of Nodemailer at https://nodemailer.com/smtp/

On line 9, I put the password of my gmail account that I am using to send emails from. Make sure you change it to yours.

On line 14-19, I created a message object. In this object, from is set to the email address of the sender, to is the email address of the receiver. subject is the subject of the email and text is the content of the email.

On line 22, I used the transport.sendMail() method to send email using Nodemailer. The first argument of the sendMail() method is the message object defined on line 14-19. The second argument is a callback function. The callback function simply checks for errors and prints a message to the console depending on whether the email was sent or not.

Now run the sendmail.js script as follows:

$ node sendmail.js

As you can see, the email was sent.

I checked my Gmail, and voila! I received the email just fine.

Sending E-Mail with Attachment Using Nodemailer:

Now that you know how to send email using Nodemailer, sending email with attachment is a piece of cake!

To send email with attachment, all you need to do is modify the message object on line 14-19 and the rest of the code should be the same.

Change the message object as follows as save the file.

Here, attachments is an array objects. Each object defines an attachment file. So you can send multiple files at once. On line 20-22, I set the relative path to a file hello.txt to the path property of the object.

Now run the sendmail.js script again.

$ node sendmail.js

As you can see, the email was sent.

As you can see, I received the message along with the attachment hello.txt.

You can also set custom name to your attachment file. For that, you have to change the attachment object as follows:

To send multiple attachments, create multiple attachment objects as follows:

That’s how you send email with attachment using Nodemailer in Node.js. Thanks for reading this article.

]]>
NodeJS Debugger Tutorial https://linuxhint.com/nodejs_debugger/ Fri, 31 Aug 2018 08:57:05 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=30006 No matter how good you are at programming NodeJS, there will always be things happening that you don’t want. So debugging a NodeJS app is very important to find and fix the problems and get the app running as soon as possible. NodeJS has powerful debugging features build in, which is really helpful. You can use the NodeJS debugger from the command line very easily.

In this article, I will show you how to use the NodeJS debugger. I am using NodeJS 8 on Debian 9 Stretch for the demonstration. But everything shown in this article should work on any latest NodeJS version on any Linux distributions, Mac OS and Windows. So Let’s get started.

Installing NodeJS:

NodeJS may not be installed on your computer by default. But it is freely available to download and install. Just go to the official website of NodeJS at https://nodejs.org/en/ and download NodeJS for your operating system. It is available for Mac OS, Linux and Windows. So no matter what operating system you have, you should be able to install it.

Setting Up the Test Program:

The NodeJS program I used in this article is given below:

This is a simple NodeJS program that adds 2 numbers.

You can run the NodeJS script app.js with the following command:

$ node app.js

In the next section, I will show you how to use the NodeJS debugger.

Starting NodeJS Debugger:

To debug the NodeJS script app.js, you have to run the script app.js with the NodeJS debugger.

You can start the NodeJS debugger for app.js the following command:

$ node inspect app.js

NOTE: On older version of NodeJS, you run node debug app.js instead to start the NodeJS debugger.

NodeJS debugger should start as you can see in the screenshot below.

Now you can run many commands here to debug the NodeJS script app.js.

Getting Help with NodeJS Debugger:

You can run the following command to get a list of commands and functions that you can use to debug a NodeJS script in the NodeJS debugger:

debug> help

As you can see, all the commands and functions with short description of what they do are listed. When you are having a hard time remembering what commands or functions to run, this is a good place to get some help.

Auto Completion on NodeJS Debugger:

You can partially type in a command or function and press <Tab> to get auto completion.

Before pressing <Tab>:

After pressing <Tab>. As you can see, the function is auto completed.

In the next sections, I will show you how to do different debugging task with NodeJS debugger.

Setting Breakpoints with NodeJS Debugger:

A NodeJS script has many numbered lines when viewed in a programming text editor. You can set breakpoints on any of these lines. Let’s say you set a breakpoint on line 3, and start the NodeJS script. Then the NodeJS debugger would run line 1 and 2 and stop at line 3. Then you can check whether the results up until this point is correct and continue the program as usual. You can set as many breakpoints as you need.

To set a breakpoint, you run the setBreakpoint() function. The function accepts an integer parameter as line number to which you want to set a breakpoint.

setBreakpoint(int lineNumber)

To set a breakpoint on line 3,

Run the following command:

debug> setBreakpoint(3)

As you can see, a breakpoint is set on line 3, which is marked by an arrow (>).

Now let’s set a breakpoint on line 22 as well:

debug> setBreakpoint(22)

As you can see, a breakpoint is set on line 22 as well, just before the first addNumber() function is executed.

Removing or Clearing Breakpoints with NodeJS Debugger:

To remove a breakpoint, just run the clearBreakpoint() function.

clearBreakpoint(int lineNumber)

Pass in the line number at which you have a breakpoint set as an argument to the function clearBreakpoint(), the breakpoint should be removed or cleared.

Listing All the Breakpoints with NodeJS Debugger:

You can list all the breakpoints you have already set with the NodeJS debugger with the following command:

debug> breakpoints

As you can see, I have breakpoints set on line 3 and line 22.

Using REPL in NodeJS Debugger:

The full form of REPL is Read–Eval–Print Loop. You can use REPL in NodeJS debugger to check the contents of variables and functions and many more. It is really useful.

To start REPL, run the following command:

debug> repl

As you can see, REPL has started.

Now you can press <Tab> twice to see what variables and functions are available at the moment in your NodeJS script.

You can also print the content of any variable you wish. Just type in the name of the variable and press <Enter>.

You can also check functions as well.

To exit REPL, press <Ctrl> + c. You should be back to the debugger.

Using the cont Command in NodeJS Debugger:

Now that you have all the breakpoints set, you can run the cont command or c command to continue running the lines till the first breakpoint.

debug> c

Now I can check the value of x and y from REPL and as you can see it is correct.

To go to the next breakpoint, you can run c command again.

The variables are printed with REPL.

Running the c command again completes the program as there are no more breakpoints.

Resetting Program Execution:

If you want to start executing lines from the beginning of your NodeJS script, you have to reset the debugger.

You can reset the debugger with the following command:

$ r

Debugging NodeJS Script Line By Line:

You can use the next or n command to run a NodeJS script line by line.

At first, I have no value set for x and y.

I executed 1 line:

debug> n

Now x is set to 5 and y is still undefined.

You can move line by line and keep debugging your NodeJS script like this.

Though there are many things I could not cover, but this is the basics of using the NodeJS debugger to debug a NodeJS app. Now it should be easy to learn more about NodeJS debugger with the help command. Thanks for reading this article. ]]> How to Install and Configure NodeJS on CentOS 7 https://linuxhint.com/install_nodejs_centos7/ Tue, 31 Jul 2018 11:38:30 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=28982 JavaScript is the programming language of the Web. It is mainly used in Web browser to make your website interactive. But a web browser is not the only place JavaScript is used these days. JavaScript can be used just like any other interpreted programming languages such as Python, Ruby etc. NodeJS made it possible. NodeJS is basically JavaScript on the server.In this article, I will show you how to install and configure NodeJS on CentOS 7. Let’s get started.

Installing Build Tools for Native Addons:

All the NodeJS modules are written in JavaScript. At times that has performance issues as JavaScript is not as fast as a compiled language such as C and C++. To solve this problem, NodeJS has native addons.

How that work is, NodeJS relies on Chrome V8 JavaScript engine, which is written in C++. So NodeJS adds an additional layer to compile JavaScript code to native binary code. This improves performance drastically. NodeJS codes runs almost as fast as C and C++ compiled code if the NodeJS module that you’re using is written using the Native Addons NodeJS API.

The NodeJS native addons needs a C++ build tool installed on your computer as the modules are built while you install them using Node Package Manager. I will show you how to install build tools here.

First update the YUM package repository cache with the following command:

$ sudo yum makecache

The YUM package repository cache should be updated.

Now install build tools on your CentOS 7 machine with the following command:

$ sudo yum install gcc-c++ make

Now press y and then press <Enter>.

The build tools should be installed.

Adding NodeJS Package Repository on CentOS 7:

At the time of this writing, you can install either NodeJS 8.x or NodeJS 10.x. NodeJS 8 is the LTS release and NodeJS 10 is latest release. Both of these versions are available to install on CentOS 7.

Add the package repository of either NodeJS 8.x or NodeJS 10.x depending on your need.

For NodeJS 8.x:

Run the following command to add the package repository of NodeJS 8.x on your CentOS 7 machine:

$ curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -

For NodeJS 10.x:

Run the following command to add the package repository of NodeJS 10.x on your CentOS 7 machine:

$ curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash -

I went for the LTS release of NodeJS, which is version 8.x. As you can see, the package repository is added.

Installing NodeJS:

Now you can install NodeJS on your CentOS 7 machine with the following command:

$ sudo yum install nodejs

Now press y and then press <Enter> to continue.

Now press y and then press <Enter> to accept the GPG key.

NodeJS should be installed.

Now run the following command to verify whether NodeJS is working:

$ node --version

As you can see, NodeJS is working properly.

Now run the following command to see whether Node Package Manager (NPM) is working:

$ npm --version

As you can see, NPM is working correctly as well.

Using NodeJS:

Now that you have NodeJS installed, I am going to show you the basics of NodeJS.

First create a project directory with the following command:

$ mkdir hello-world

Now navigate to the project directory:

$ cd hello-world/

Inside hello-world/ directory, initialize a Node package.json file with the following command:

$ npm init -y

As you can see a package.json file is generated. The contents of the file are also printed on the terminal. It is a JSON file. Here, name is the application name, version is the application version, description is a short description about your application, main is the name of a NodeJS script in your project directory that is used to start your application. By default, it is index.js, but you can change it. scripts is an object that holds command aliases. I am going to leave the defaults for now.

Now install Express.js NodeJS package with NPM with the following command:

$ sudo npm install express --save

Express should be installed.

All the modules are kept in the node_modules/ directory in your project directory.

Now create a index.js file and type in the following codes:

let express = require('express');
let app = express();

app.get('/', (req, res) => {
res.end('<h1>Welcome to LinuxHint</h1>');
});

app.listen(8080, () => {
console.log('App is running on http://localhost:8080');
});

Now run the following command to start the app:

$ node index.js

The app should start.

Now from your web browser, go to http://localhost:8080 and you should see the following output. The NodeJS app is working correctly.

Now to stop the app, press <Ctrl> + c on the terminal.

Now if you visit http://localhost:8080 from the web browser, you should see an error.

That’s how you install and configure NodeJS on CentOS 7. Thanks for reading this article.

]]>
Install NPM on Debian 9 https://linuxhint.com/install_npm_debian/ Sun, 20 May 2018 05:39:18 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=26515

How to Install and Use NPM on Debian 9 Stretch

NPM or Node Package Manager is the same thing as APT to Debian. It is used to install, remove, update NodeJS packages.  In this article, I will show you how to install and use NPM on Debian 9 Stretch.

Installing NodeJS and NPM

The version of NodeJS available in the official Debian 9 Stretch package repository is 4.x, which is very old. The official package repository of Debian 9 Stretch does not have NPM.  In this section, I will install the latest stable version of NodeJS and NPM which is at the time of this writing 8.11.1.

First update the apt package repository cache with the following command:

$ sudo apt-get update

Now install CURL with the following command:

$ sudo apt-get install curl

Press y and then press <Enter> to continue.

CURL should be installed.

Now add the package repository of NodeJS 8.x with the following command:

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

The NodeJS 8.x package repository should be added as you can see from the screenshot below.

Now you can install NodeJS and NPM all together along with the development tools for building native NodeJS modules with the following command:

$ sudo apt-get install build-essential nodejs

Now press y and then press <Enter> to continue.

NodeJS, NPM and the required build tools for compiling NodeJS native modules are installed.

Now check whether NodeJS is working with the following command:

$ node --version

As you can see, NodeJS 8.11.1 is installed and working correctly.

Now check whether NPM is working with the following command:

$ npm --version

As you can see NPM is installed correctly as well.

Using NPM

In this section, I will show you how to use NPM to manager NodeJS modules or packages. Before that, let’s talk about global packages and local packages.

If you install a NodeJS package globally, then it should be saved somewhere /usr/lib/node_modules directory and you can access it from any NodeJS project.

If you install a NodeJS package locally, then a directory node_modules/ should be created on your project directory and the package should be saved in node_modules/ directory relative to your project directory. It can only be accessed from that project.

That’s all you need to know for now. Let’s continue.

Creating a package.json Configuration File with NPM:

Every NodeJS project has a package.json file in its project’s root directory. This file holds information about your project, such as the name of the project, the version of the project, the dependencies or other NodeJS packages your project depends on and many more.  You can manually create a package.json file and put all these information or you can use NPM to create it for you.

First create a new directory node-project (you can name is whatever you want) for your NodeJS project with the following command:

$ mkdir node-project

Now navigate to your project directory with the following command:

$ cd node-project

Now to create a package.json file with NPM, run the following command:

$ npm init

Fill in the details and press <Enter> to move forward.

In the end, type in yes and press <Enter>.

As you can see, a package.json file is created.

This is the contents of the package.json file:

Installing a NodeJS Package Locally with NPM:

If you know the name of the package, then you can easily install it using NPM.

For example, if you want to install express NodeJS package, which is Express web framework, run the following command from your project directory:

$ npm install express --save

express NodeJS package should be installed.

Installing a NodeJS Package Globally with NPM:

You can install a NodeJS package globally from any directory.  For example, if you want to install express NodeJS package globally, run the following command:

$ sudo npm -g install express

It should be installed globally.

Removing a NodeJS Package Locally with NPM:

If you want to remove a NodeJS package, let’s say express, from your project directory, run the following command from your project directory:

$ npm uninstall express --save

The express NodeJS package is removed.

Removing a NodeJS Package Globally with NPM:

To remove a NodeJS package, let’s say express, globally, run the following command:

$ sudo npm -g uninstall express

It should be removed.

Searching for NodeJS Packages:

Well, now you know how to install and remove NodeJS packages with NPM. Now the question is, how do I know what I can install with NPM? What packages are available?

Well, you can search for packages in the NPM’s official website at https://www.npmjs.com/ or you can use NPM command line utility.

To search for NodeJS packages from your web browser, go to https://www.npmjs.com/ and search for what you’re looking for. Type in the keywords as marked in the screenshot below, and press <Enter>.

You should see a lot of packages as you can see in the marked section of the screenshot below. You can click on any one of them to see more information about that package.

You can also run the following command to search for NPM packages:

$ npm search "Web framework"

As you can see, the same list is displayed. You can pick up the package name from the first column as marked in the screenshot below, and install what you need using NPM.

So that’s how you install and use NPM on Debian 9 Stretch. Thanks for reading this article.

]]>
What is NodeJS? https://linuxhint.com/what_is_nodejs/ Sun, 13 May 2018 04:30:58 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=26068

In this tutorial, we will get started with Node.js. Learn about some of its most popular features and will try to motivate the readers to adopt this wonderful technology for their future projects. As a prerequisite, you just need to have a passing familiarity with JavaScript and generic programming concepts, such as variables, data types and functions.

JavaScript has a strange history. It started off as a light-weight scripting language for web browsers and was treated more like a ‘toy’ than a serious programming language. But it has long since outgrown its humble beginning.

People started extending its capabilities when Google open-sourced Chrome’s JavaScript interpreter — The V8 engine. Node.js takes this JavaScript engine and extends it to work outside the realm of the browser. Node.js binds JavaScript with your operating system’s API so it can run natively on the server (or in case of a developer, on his/her desktop). Yes, this means you can implement server-side applications, desktop applications and back-end mechanisms by learning just one language — JavaScript.

Simply put, you can write .js files which contains programs written in JavaScript syntax that will get interpreted by Node.js much the same way as .py files with valid syntax are interpreted/executed by python interpreter.

There’s more to it than just knowing the language, however, Node.js has unfamiliar modules and concepts that would require patience in an unending cycle of learning new concepts. It has its own package manager (npm), version manager (nvm) and the world largest package registry. Rest assured, the initial difficulty will make your life a lot easier over the long run.

Installation

Currently there are two options for Node.js versions which you might want to consider.

  • Version 8.11.1 LTS (Recommended for most users)
  • Version 10.0.0 Current (Offers latest set of features, but not meant for production grade applications)

We will be sticking with the LTS version. Downloading Node from the official site for your operating system would also install the Node Package Manager (npm). It is difficult to talk about Node.js without getting into npm. We will come back to the package manager later on. If you are using Ubuntu or any other debian distro simply use:

$ sudo apt install nodejs

For all the binaries and the source code visit the official download page.

That’s it with installation, time to say, “Hello, World!”

Hello, World! And Creating a Server

As promised, we will be creating a hello.js file and run it using Node. In a plain text file, called hello.js, we write the following line:

console.log(“Hello, World!);

Now save the file and open a terminal in the same directory as that file and run the following command:

$node hello.js
#Or you may run
$node hello

This will give you the desired output of “Hello, World”. Just like vanilla JavaScript. But surely, we can do better…

Unlike PHP based applications which require Apache or Nginx or some other web server program to run atop, in node we write our own http routes, configure the ports and hostnames and process HTTP requests to give appropriate responses.

Sounds like a lot of work, but it is only an initial hurdle in the learning curve, and once you get a hang of things, you will be able to understand web applications in greater  depths than ever before. Let’s create a web server which listens on port 3000 on localhost and returns a text file as a response. Create a file app.js with the following contents:

const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

Before we get into the details of the code, save this file and open a terminal in the same directory as the file, then run:

$ node app

This will execute the contents of app.js file and you will get an output as follows:

Open a web browser and visit http://localhost:3000/ or http://127.0.0.1:3000/ to see a simple Hello World text on your browser window.

So what did we just do? Well, if you are familiar with JavaScript, you can probably make sense of some of it..

The first line imports the http module, which is an in-built module that comes along with Node, and it helps us listen on web sockets for requests, process http requests, and give appropriate responses.

The second and third line sets the hostname to ‘127.0.0.1’ and port  to 3000. This means we can keep reusing the variable hostname and port, instead of typing out the entire IP address. Later on, when you are actually deploying it on a server, you will replace it with the server’s IP address and a port number like 80 or 443 if it is a web server. The keyword const ensures that the variable cannot be changed elsewhere in the program.

The lines four to eight  creates a server object which takes request as req and gives response as res.

The response has a statusCode attribute to it, the res.statusCode which is set to 200 which the client interprets as “Okay” status. Error codes are 400s and 500s, for example, Error 404 is code for resource not found. Similarly, the setHeader attribute is set to ‘text/plain’ which means that the client will receive plain text. You can set this to HTML and your browser will render any valid html that the server responds with. And the end attribute is simply the text that we want to return. Instead of having a string here, real-world applications will have a static HTML file or another .js file for the client browser, which would constitute a much more useful response.

Finally, the last three lines starts the server and prints a message saying that it is active on a specific hostname and port number as set by const statements, initially. Everytime a new request comes in at the specified hostname:port combination server gives responds with appropriate response object.

What it implies?

You don’t need to understand the above code in its entirety to know the implications. We already have JavaScript on the front-end thanks to awesome frameworks like Angular and React. Along with that, we also have back-end functionalities baked into the Node.js ethos.

Web frameworks like Express.js can help you write even more complex application on top of Node.js. Fetching data from Database, creating APIs, and the front-end UI all can be written using one language.

The Power of V8

Despite all of it being a single language, there’s still a lot to learn. Different frameworks and modules have different functionalities. There are a tonne of versions to keep track of. So is there any other benefit of using the Node.js ecosystem.

One of the most important argument in support of it is that the V8 engine has an excellent support for asynchronous, non-blocking I/O. Which basically means that it a single process running on your system memory can handle multiple incoming requests What it roughly means is that if one request is being processed, and another request comes in, Node has the capability to start processing the new request even if the first request is not yet finished.

Moreover, a single process running in your memory is responsible for handling all the incoming request. Unlike PHP based applications which spawns a new process for every new incoming request.

Hopefully, this intro was enough to get you motivated about Node.js. Let’s know if you want more in-depth tutorials on similar topics by following us on Twitter, Facebook and YouTube.

]]>
How to Update NPM Packages https://linuxhint.com/how-to-update-npm-packages/ Tue, 06 Mar 2018 13:12:33 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=23388

Updating npm packages in Ubuntu 16.04

Node Package Manager, or npm, gets installed along with Node.js and you can use it to import software packages built on top of Node.js.

If you are not familiar with the idea of nodejs, it is based off of Google Chrome’s JavaScript engine and can be used for server side scripting using JavaScript. It brings JavaScript (which traditionally runs on the client e.g a web browser) at the same footing as any other server side language like .NET or php.

Because the language is already very popular and easy to use. There are now a myriad of applications built on top of the Node.js to the point that it almost has its own ecosystem of applications and frameworks to build applications each bundled as its own package. The problem with that arises when developers start to improve upon their packages and releases new version.

Like most package managers, npm installs the most recent (stable) release of a package. So if you install a particular version of Express for your web application and a few years later after a new version of Express, chances are somethings in your app might break in a direct or indirect way.

To circumvent this issue, it is handy to use npm in a way that makes use of version numbers to keep track of packages.

Installing Node.js and npm

If you don’t already have Node.js installed in your system it is a good idea to start with the official LTS release. The official repository of Ubuntu 16.04 is a bit behind from the latest stable release and we would thus add the Node.js official repo as a PPA.

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

The above command fetches a shell script from deb.nodesource.com and runs it via bash. The script automatically adds the public keys of the repo and updates the source lists for apt package manager.

After this installing Node.js and npm is as easy as running:

$apt install nodejs

Now before we get started with installing and updating various packages, let’s make sure that the version of npm and Node.js is what we desire them to be.

$nodejs --version
$npm --version

The version of npm is not the latest stable release (although we made sure that Node.js is  the LTS version)

To update npm itself you can run the command:

$sudo npm install npm@latest -g

Where the -g flag makes sure that the package is installed globally, that is, for all the users. You can only do this if you are the root user or have root previleges of the system. After which you can see that the version number for npm has changed.

If you would like to go back you can enter the previous version number in a similar fashion. For example:

$sudo npm install npm@5.6.0 -g

Installing and updating local packages

npm offers 2 different methods for installing packages. First is locally to be used in, say, another software that you are trying to build and the second method for installing it is to do it across the system for all users. This is great if you are trying to install a system utility, say with a CLI interface, to be used as a basic command or a standalone software.

The local packages are directory specific. For example, if you are building a Node.js app first make project folder or directory:

$mkdir myapp
$cd myapp

Now, from inside the directory you can run an npm init command and enter appropriate values for the name, description, git repository and other relevant fields which are the metadata of the package.

Now if you install a package, such as lodash by running the following command in the directory:

$npm install lodash

npm automatically gets the latest stable release of the said package and installs it for you.

If you want to check the version number then, enter the command:

$npm list

If a new version of lodash comes along and you wish to upgrade then, in the same directory, run:

$npm update

Now you can see that the version number is greater than what it was before.

If something is wrong with the new version and you are facing issues, then you can always go back to previous state by simply running.

$npm install lodash@4.17.0

Of course, that would require keeping track of the previous version number. Performing a git commit before any of the npm update actions is advisable for this reason.

Installing and updating global packages

Installing packages globally is actually much simpler since these are usually standalone utility. A great example of such a package is gtop which is similar to the top  utility in Linux. It shows all the resource utilization in a clean and elegant way.

To install a package globally, either be the root user or prefix your command with sudo if you are a user with root previleges.

$sudo npm install gtop -g

Now, like any command utility, you can call upon gtop by running:

$gtop

To exit simple hit q and you will fall back to the terminal. Because there are too many dependencies for gtop simply running npm list -g won’t help us know the verison of gtop. So we can try this instead:

$npm list gtop -g

If you want to update the package,then simply run:

$sudo npm update gtop -g

And you are done!

Conclusion

So that’s basic package management if you want to use npm packages for your new software project or as a standalone system utility. If you wish to explore npm packages you can always do so by going to their official website.

]]>
PostgreSQL NodeJS Tutorial https://linuxhint.com/postgresql-nodejs-tutorial/ Thu, 18 Jan 2018 08:39:10 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=21630

Using PostgreSQL from Node.js

PostgreSQL is a very popular open source database. It is widely used for almost all types of applications. Node.js has very good modules to work with PostgreSQL database. In this article, I am going to show you how to connect to a PostgreSQL database from Node.js. I will use a Node.js module called ‘node-postgres’ to integrate Node.js and PostgreSQL.  Let’s get started.

Pre-requisites:

First you have to make sure that Node.js, NPM and PostgreSQL are installed and running. You can install and configure PostgreSQL from How to Install PostgreSQL on Ubuntu Linux: The Easy Way and Node.js and NPM from How to install NPM if you don’t have them installed already.

Now check whether Node.js is working with the following command:

$ node --version

Now check whether NPM is working with the following command:

$ npm --version

Now check whether PostgreSQL is working with the following command:

Now create a directory ‘postgre-node’.

Then navigate to the directory you just created with the following command:

$ cd Documents/postgre-node

Then you should run the following command to create a ‘package.json’ file.

$ npm init -y

You can see from the screenshot below that a ‘package.json’ file is created.

Now install ‘node-postgres’ Node.js module using NPM with the following command. If you remember, ‘node-postgres’ is a PostgreSQL Client for Node.js.

$ npm install --save pg

‘node-postgres’ should be installed.

Using ‘node-postgres’ PostgreSQL Node.js Client:

Now inside the directory ‘postgres-node’, create a new file ‘index.js’ and write the following codes as shown in the screenshot below.

const pg = require(‘pg’);
const pool = new pg.Pool({
user: ‘sysadmin’,
host: ‘127.0.0.1’,
database: ‘mywebstore’,
password: ‘123’,
port: ‘5432’});

pool.query(“SELECT NOW()”, (err, res) => {
console.log(err, res);
pool.end();
});

Here const pg = require(‘pg’) imports ‘node-postgres’ Node.js module.

Then I created a Pool using pg.Pool with PostgreSQL login credentials. I didn’t change anything from the article for setting up PostgreSQL in the “Pre-requisites” section. You may take a look at it again.

I simply retrieved the current date and time using the PostgreSQL NOW() function using pool.query()method of ‘node-postgres’.

I ran SQL statements “SELECT NOW()”.

Now if I save the ‘index.js’ file and run the Node.js source file with the following command:

$ node index.js

You should see current TIMESTAMP on the output as shown in the screenshot below.

Creating a Table:

Now I am going to create a new Table ‘users’ using the following query:

# CREATE TABLE users(id SERIAL PRIMARY KEY, firstName VARCHAR(40) NOT NULL,
lastName VARCHAR(40) NOT NULL)

The ‘users’ table has 3 fields, id, firstName and lastName. id is an integer and firstName and lastName fields are strings.

The source code is given on the screenshot given below.

const pg = require(‘pg’);
const pool = new pg.Pool({
user: ‘sysadmin’,
host: ‘127.0.0.1’,
database: ‘mywebstore’,
password: ‘123’,
port: ‘5432’});
pool.query(“CREATE TABLE users(id SERIAL PRIMARY KEY, firstname VARCHAR(40) NOT NULL,
lastName VARCHAR(40) NOT NULL)”, (err, res) => {
console.log(err, res);
pool.end();
});

Now if I run the code, you should see the following output.

Now let’s login to the ‘mywebstore’ datastore as ‘sysadmin’ user with the following command:

$ psql -U sysadmin -h127.0.0.1 mywebstore

It should ask you for the ‘mywebstore’ datastore’s password. Type in the password and press <Enter>

You should be logged into the PostgreSQL console as shown in the screen below.

Now run the following command to see all the tables:

mywebstore=> \dt

You should see ‘users’ table as shown in the screenshot.

You can run the following command to quit PostgreSQL command line interface:

mywebstore=> \q

Inserting into Table:

Now you can insert into the ‘users’ table with the following command:

# INSERT INTO users(id, firstName, lastName) VALUES(1, ‘Shahriar’, ‘Shovon’)

The source code is given in the screenshot below.

Now if you run the source code, you should see the following output.

Now you can login to the PostgreSQL command line interface with the following command like before:

$ psql -U sysadmin -h127.0.0.1 mywebstore

Run the following SQL query:

$ SELECT * FROM users;

You should see the data you inserted as shown in the screenshot below.

Retrieving Data from PostgreSQL:

You simply execute the following SQL statement to retrieve the data:

# SELECT * FROM users;

The other steps are similar. So I am not going to explain them again as it is out of scope of this article.

Updating data:

To update an existing row of PostgreSQL’s users table, run the following SQL query:

# UPDATE users SET firstName=’Shovon’, lastName=’Shahriar’ WHERE id=1

Here ‘id’ is the primary key which is unique to each column of the users table.

After you run this code, firstName and lastName should be updated as shown in the screenshot below.

Deleting a Column from PostgreSQL:

You can run the following SQL statement to delete a column from the PostgreSQL.

# DELETE FROM users WHERE id=1

Here id is the primary key of the users table.

Once you login to the PostgreSQL command line interface, you should not find the row you just deleted. In this case, I have an empty table. Because I had only 1 row in the users table.

That’s how you perform CRUD operation with PostgreSQL using Node.js, and thanks for reading this article.

]]>
Install NPM NodeJS Package Manager on Ubuntu https://linuxhint.com/install-npm-nodejs-package-manager-on-ubuntu/ Mon, 15 Jan 2018 06:14:38 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=21525

How to Install and Use NPM (Node Package Manager) on Ubuntu 17.10

JavaScript is one of the most popular programming language in the world. No wonder that it’s so popular. It is the only programming language that web browsers understand. Every website in the world uses JavaScript to deliver interactive content to the visitors. Without JavaScript you would have a plain website and the page would reload every time you clicked. The web would not be what it is now.

But there is a problem with JavaScript. It runs on a Web Browser only. So on the server side you had to use something like PHP, Java, Python, Ruby and other programming languages. For a long time, developers wanted to use their favorite JavaScript on the server instead of PHP, Java and other programming languages. Node.js is one of the solutions for JavaScript on the server.

Node.js is very modular in nature. The language provides only the basic functionalities and it’s easily extended through the use of Node modules. There are a lot of Node modules that you can choose from. If you’re a developer, you should find some module or many that does what you want. But where do you find these modules? Well, there’s a repository where all the Node.js modules are kept. You can go to https://www.npmjs.com to search for Node.js modules.

Since Node.js is a modular language, and can be extended with Node.js modules, each of these modules depend on other Node.js modules. Installing Node.js modules manually is a tedious task and very impractical. This is where a Node Package Manager or NPM in short, comes in. With NPM, you can easily install, remove, update any module you want.

In this article, I am going to show you how to install and use NPM on Ubuntu 17.10 Artful Aardvark. Let’s get started.

Installing NPM:

NPM is available on the official package repository of Ubuntu 17.10 Artful Aardvark.

First update your package repository cache with the following command:

$ sudo apt-get update

Since NPM is a Node.js package manager, there’s no point in installing only NPM. So you can install Node.js and NPM together with the following command:

$ sudo apt-get install nodejs npm

Press ‘y’ and then <Enter> to continue.

Node.js and NPM should be installed.

Now run the following command to verify whether Node.js is working correctly.

$ node --version

You should see similar output as shown in the screenshot. It means Node.js is working correctly.

Now do the same for NPM with the following command:

$ npm --version

So NPM is working correctly as well.

Searching for Node.js Modules:

You can search for a Node.js module using NPM without going to https://www.npmjs.com

First update the NPM package repository cache with the following command:

$ npm update

Now to search for a Node.js module with NPM, run the following command:

$ npm search YOUR_QUERY

Let’s say you’re looking for a web framework; you would run the following command:

$ npm search “web framework”

You can see that search result is shown.

Installing Node.js Module using NPM:

You can install a Node.js module globally or locally. The difference is that, global node modules can be accessed like any other commands, but it’s not the case for locally installed modules. Soon you will see the difference.

I am going to install “express” module locally to show you how to install Node.js module with NPM.

Before I go any further, I am going to create a directory for my Node.js project and navigate to the directory.

$ mkdir node-demo && cd node-demo

Now to install ‘express’ using NPM, run the following command:

$ npm install express

‘express’ module should be installed and it should be stored in the ‘node_modules’ directory as shown in the screenshot below. When you install it locally, this subdirectory is created.

You can also install a module globally. Let’s say you want to install ‘express-generator’ globally, you would be running the following command:

$ sudo npm -g install express-generator

‘express-generator’ is installed.

Now ‘express-generator’ can be accessed from the command line.

Removing Node.js module with NPM:

You can remove a local Node.js module with NPM with the following command:

$ npm remove express

‘express’ is removed.

To remove ‘express-generator’ global Node.js module, you can run the following command:

$ sudo npm -g remove express-generator

‘express-generator’ is removed.

Listing installed Node.js Modules with NPM:

You can list locally installed Node.js Modules with the following command:

$ npm list

You can install globally installed Node.js Modules with the following command:

$ npm -g list

That’s how you install and use NPM on Ubuntu 17.10 Artful Aardvark. Thanks for reading this article.

]]>
Install and Getting Started with NodeJS on Ubuntu https://linuxhint.com/install-nodejs-ubuntu-getting-started/ Wed, 10 Jan 2018 14:02:15 +0000 https://linuxhint-com.zk153f8d-liquidwebsites.com/?p=21399

Get started with NodeJS on Ubuntu

NodeJS is an open-source server side framework built on JavaScript under MIT (Massachusetts Institute of Technology) license.  It is mainly used for asynchronous programming and it is a very light weight framework that makes it faster than other frameworks. It is also supported by most of the popular operating systems. Different types of applications like web application, command line application, RESTful API etc. can be developed with this framework. How you can easily install and use this framework on Ubuntu are shown in this article.

NodeJS Installation Steps

1. Press Ctrl+Alt+T to open the terminal and run the following command to install NodeJS

$ sudo apt-get install -y nodejs

After completing the installation process, type the following command to check the version of the installed framework.

$ nodejs -v

2. To install necessary modules and packages you will need to install NodeJS package manager called npm. Run the following commands to install the npm.

$ sudo npm install npm –global

Check the version of npm.

$ npm -v

Now, NodeJS is ready to use for developing any application. How you can apply NodeJS as a beginner is shown in the next part of this article.

Using NodeJS

 You can use NodeJS for various types of application development.  As a beginner, how you can create a simple console application and a web server are shown in this part.

Creating Console application

 Run the following commands to create a directory named nodejsapp for keeping your code organized, go to the newly created directory and open the nano editor for creating a JavaScript file named firstapp.js.

$ mkdir nodejsapp
$ cd nodejsapp
$ nano firstapp.js

Write the following code in the file to print a output in the console. Press Ctrl+x and then y to save the file and exit from the editor.

console.log('First NodeJS Application');

Run the following command to execute the code of the firstapp.js file.

$ nodejs firstapp.js

if you get any permission problem to execute the script then you have to run the following command for setting execution permission of firstapp.js file and again run the above command.

$ chmod +x firstapp.js

Creating Local Web Server

JavaScript is a popular client side scripting language which doesn’t require any web server to run. Web server is required to run any server side scripting language like php, asp etc. and you need to install a particular web server to run server side scripts. Using NodeJS framework, you can easily implement a local web server which can be used to run server side script.

Open nano editor to create a new JavaScript file named server.js that will be used to create a local web server.

$ nano server.js

Add the following code in the file to create the server connection on port number 6060. According to this code, NodeJS will listen for server connection at localhost:6060 and if the connection can be established successfully then 200 code will be generated and ‘NodeJS App’ will be shown as output.

var http = require('http');

var server = http.createServer(function(request response) {
resquest.writeHead(200,{'Content-Type': 'text/plain'});
response.end('NodeJS App');
});
server.listen(6060);
console.log('Server is running at http://localhost:6060/');

Save the file by pressing Ctrl+x and y. Now, execute the following command to run the web server. If the code executes properly then the message ‘Server is running at http://localhost:6060’  will be displayed in the console.

$ nodejs server.js

Open any browser to check the web server code is working properly or not.  The script will return ‘NodeJS App’as content in the browser if the above code executes properly. Type the following URL in the address bar for checking.

http://localhost:6060

In the above example, a simple static text is displayed in the browser which is added as the content with response. But generally, any index file displays when the base URL executes. So, how you can attach any html file in the server connection script is shown in the next part.

At first, create a very simple html file named index.html using Text Editor with the following code and save it in the nodejsapp directory which is created previously.

<html>
<body>
    <center>
    <h2>Testing NodeJS Application </h2>
    <p> This is my first web application using NodeJS </p>
    </center>
</body>
</html>

Now, create another JavaScript file named server2.js with the following code to view index.html file, after creating web server connection. Here, fs module is used to read the index.html file. Three types of outputs can be generated based on the code. If the connection establishes properly and index.html file exists then it will load the content of index.html file in the browser. If the connection establishes but index.html file does not exist on the current location then ‘Page is not found’ message will print.  If the connection establishes and index.html file also exists but requested url is not correct then ‘Default content’ text will display as by default content. Port number 5000 is set as listening port here. So when web server connection establishes successfully then the message ‘Server is listening on 5000’ will show in the console.

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

var server = http.createServer(function (request, response) {

    if (request.url === "/") {
        fs.readFile("index.html", function (error, pgResp) {
            if (error) {
                response.writeHead(404);
                response.write('Page is not found');
            } else {
                response.writeHead(200, { 'Content-Type': 'text/html' });
                response.write(pgResp);
            }

            response.end();
        });
    } else {

        response.writeHead(200, { 'Content-Type': 'text/html' });
        response.write('<h1>Default Content</h1>');
        response.end();
    }
});

server.listen(5000);

console.log('Server is listening on 5000');

Save the file and exit from the editor. Run the server by executing the following command.

$ nodejs server2.js


Type the following URL to view the content of index.html file in the browser.

http://localhost:5000

Now, insert an invalid URL in the browser and check the output.

http://localhost:5000/test

Now modify server2.js file and set the file name as index2.html that does not exit and restart the server. Type the base URL again to check the output.

NodeJS is a demanding framework and you can perform many tasks using it. As a beginner, you can follow the steps which are shown in this article to start application development using NodeJS.

]]>
How to install the latest Node.js on Linux? https://linuxhint.com/how-to-install-latest-node-js-on-linux/ Mon, 02 Jan 2017 21:13:40 +0000 http://sysads.co.uk/?p=16990

Node.js is a runtime JavaScript environment that is used on the server-side. Node.js is a full-stack software building solution but is mostly used at the back end to build the applications. Node.js uses the NPM package manager as a default package manager, which is known as the most used software registry.

There are several methods to install Node.js on Ubuntu 20.04 LTS, but here, we will learn the two most efficient and easiest methods to install it.

  • Using APT package repository
  • Using the APT package repository through NodeSource PPA

Let’s get started with the easiest one.

Install Node.js on Ubuntu 20.04 using APT

Installing any software through the APT package repository is the easiest way to install the software on Ubuntu. First, update the system’s package repository.

$ sudo apt update

Then, install the Node.js using the simple apt install command with the sudo privileges.

$ sudo apt install nodejs -y

In this command, the “-y” flag is added to automatically answer “yes” if any prompt occurs.

After installing the Nodejs, if you want to install NPM as well, run the command.

$ sudo apt install npm -y

After a while, NPM will be installed as well.

The above two commands will install all the other tools required for compilation.

To verify and check the versions of the Node.js and NPM, execute the following two commands.

$ nodejs --version

$ npm --version

As you can see, version 10.19.0 of Node.js and version 6.14.4 of NPM is installed.

Install Node.js on Ubuntu 20.04 through NodeSource PPA

In case you want to install some specific or older version of Node.js, it is better recommended that you use the official Private Package Archive(PPA) managed by the NodeSource.

At the date of writing this post, NodeSource has the following Node.js versions available:

  • Node.js v15.x
  • Node.js v14.x
  • Node.js v12.x
  • Node.js v10.x

Furthermore, you can check the version provided by the NodeSource by visiting their Github page (GitHub – nodesource/distributions: NodeSource Node.js Binary Distributions).

For example, to install the Node.js v15.x, you first need to have the curl installed on your system.

To install curl, perform the following.

$ sudo apt install curl -y

After installing the curl, execute the following command to run Nodesource’s installation script using the curl command.

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

Once the NodeSource’s PPA is configured for Node.js on your system, now install the Node.js by typing the following command.

$ sudo apt install nodejs -y

Let’s verify the versions of Node.js and NPM by typing the commands.

$ node --version
$ npm --version

You can witness that the required versions are installed successfully.

Wrap up

These are the two different methods to install Node.js on Ubuntu 20.04 LTS. You can either install it via the APT package repository, which is the easiest way, or go with your desired version with the official PPA introduced by NodeSource.

]]>