Nodejs – TecAdmin https://tecadmin.net How to guide for System Administrator's and Developers Thu, 15 Dec 2022 07:59:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 How to Install Grunt on Ubuntu 22.04 & 20.04 https://tecadmin.net/how-to-install-grunt-on-ubuntu-22-04/ https://tecadmin.net/how-to-install-grunt-on-ubuntu-22-04/#respond Tue, 19 Jul 2022 05:33:58 +0000 https://tecadmin.net/?p=30418 Grunt is a node-based task runner that helps developers automate common tasks during the software development process. It can be used to compile code, run tests, and more. grunt is easy to install and configure, and it can be used with any programming language. Grunt is available as a free, open-source tool, that is typically [...]

The post How to Install Grunt on Ubuntu 22.04 & 20.04 appeared first on TecAdmin.

]]>
Grunt is a node-based task runner that helps developers automate common tasks during the software development process. It can be used to compile code, run tests, and more. grunt is easy to install and configure, and it can be used with any programming language.

Grunt is available as a free, open-source tool, that is typically used in conjunction with other tools, such as Git and npm. A grunt is a powerful tool that can help developers save time and improve their workflow.

In this blog post, you will learn to install Grunt on Ubuntu systems.

Prerequsities

Assuming you already have Node.js and NPM installed on your system. Otherwise, you can visit our other tutorial to install Node.js on Ubuntu systems.

Verify the Node.js and NPM versions:

node --version 
npm  --version 

Installing Grunt CLI

Once you have verified that Node.js and NPM are on your system. Use the following command to install Grun CLI on your system globally.

npm install grunt-cli --location=global 

After successfully installation, check the installed version of Grunt-cli:

grunt --version 
Output
grunt-cli v1.4.3

Now, you add the "scripts": { "test": "grunt test" } to the package.json. Now, run “npm test” to initiate the grun test command.

Enable Shell Auto-completion

You can also enable the tab auto-completion for Grunt, and add one of the following lines to your ~/.bashrc or ~/.zshrc file based on your active shell.

  • Bash shell users edit ~/.bashrc and apped the following code
    eval "$(grunt --completion=bash)"
  • Zsh shell users edit ~/.zshrc and apped the following code
    eval "$(grunt --completion=zsh)"

Conclusion

In this tutorial, you have learned to install Grunt-CLI on your Ubuntu system. Also configured the tab auto-completion.

The post How to Install Grunt on Ubuntu 22.04 & 20.04 appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-install-grunt-on-ubuntu-22-04/feed/ 0
How to Install Bower on Ubuntu 22.04 & 20.04 https://tecadmin.net/how-to-install-bower-on-ubuntu-22-04/ https://tecadmin.net/how-to-install-bower-on-ubuntu-22-04/#respond Sat, 02 Jul 2022 04:57:22 +0000 https://tecadmin.net/?p=30350 Bower is a package manager for front-end development that allows you to manage your dependencies and includes features like versioning, downloading from GitHub, and more. It’s popular among web developers because it makes managing project dependencies easy and efficient. In this tutorial, we’ll show you how to install Bower on Ubuntu 22.04. We’ll also show [...]

The post How to Install Bower on Ubuntu 22.04 & 20.04 appeared first on TecAdmin.

]]>
Bower is a package manager for front-end development that allows you to manage your dependencies and includes features like versioning, downloading from GitHub, and more. It’s popular among web developers because it makes managing project dependencies easy and efficient.

In this tutorial, we’ll show you how to install Bower on Ubuntu 22.04. We’ll also show you how to use it to install packages and manage your dependencies. Let’s get started!

Step 1 – Installing Node.js

Node.js is the primary requirement for running Angular applications. You can install the required Node.js using NVM command-line utility. Log in to your Ubuntu system and follow:

  1. Use the following command to install NVM:
    curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash 
    
  2. Now activate the NVM enviornemnt on your system.
    source ~/.bashrc
    
  3. As of today, Angular 14 is the latest version that suport Node.js 14 LTS and 16 LTS versions. Following command will install Node.js 16 on your system.
    nvm install v16
    

Step 2 – Installing Bower on Ubuntu

After installation of node.js and npm on your system, use the following commands to install bower.

npm install bower  --location=global  

Now, You have successfully installed the bower. Let’s check the installed version of the bower on your system using the following command.

bower --version 
Output
1.8.14

Step 3 – Using Bower in Applicaiton

As you are already aware that Bower is a package management utility. It stores the details of the package under bower.json file.

Here are the quick references for using bower:

  • The following command creates a bower.json file for your package with bower init.
    bower init 
    
  • To Install all packages defined under bower.josn file, run below command:
    bower install 
    
  • Search for a specific package
    bower search phpmailer
    
  • This command will install defined package and save the reference in bower.json.
    bower install phpmailer --save 
    
  • Installing bower package from Github repository.
    bower install git://github.com/user/package.git 
    
  • Installing bower package from a URL.
    bower install http://example.com/script.js 
    

Conclusion

In conclusion, this article has shown you how to install the Bower on Ubuntu 22.04. If you run into any problems or have any questions, please leave a comment below and I will do my best to help you out. Thanks for reading!

The post How to Install Bower on Ubuntu 22.04 & 20.04 appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-install-bower-on-ubuntu-22-04/feed/ 0
How to Install Latest Node.js on Ubuntu https://tecadmin.net/install-latest-nodejs-npm-on-ubuntu/ https://tecadmin.net/install-latest-nodejs-npm-on-ubuntu/#comments Tue, 14 Jun 2022 13:10:38 +0000 https://tecadmin.net/?p=5145 If you’ve been exploring the world of front-end and JavaScript, you might have come across Node.js. It is a server-side framework that uses Google’s V8 engine to execute JavaScript code. Developers can use Node.js as it provides them with an easy way to build fast and scalable network applications, using single-threaded asynchronous events. In this [...]

The post How to Install Latest Node.js on Ubuntu appeared first on TecAdmin.

]]>
If you’ve been exploring the world of front-end and JavaScript, you might have come across Node.js. It is a server-side framework that uses Google’s V8 engine to execute JavaScript code. Developers can use Node.js as it provides them with an easy way to build fast and scalable network applications, using single-threaded asynchronous events.

In this article, we will see how to install Node.js on Ubuntu and its derivatives via a new official PPA repository. If you are new to Ubuntu or any other Linux operating system, then be sure to check out our beginner’s guide first.

You can also use the popular Node Version Manager (NVM) for installing specific Node.js version on your system.

Step 1 – Configuring Node.Js PPA

Node.js releases are available in two types, one is the LTS release, and the other is the current release. Choose any one version of your choice or as per the project requirements. Let’s add the PPA to your system to install Nodejs on Ubuntu.

  • Use Current Release – During the last update of this tutorial, Node.js 19 is the current Node.js version available.
    sudo apt install -y curl 
    curl -sL https://deb.nodesource.com/setup_19.x | sudo -E bash - 
    
  • Use LTS Release – Instead of the current release, it’s a good idea to use a stable version. During the last update of this tutorial, Node.js 18 is the latest LTS release available.
    sudo apt install -y curl 
    curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash - 
    

For this tutorial, I am using the latest current release and added their PPA to my system.

Step 2 – Install Node.js on Ubuntu

You have successfully configured Node.js PPA in your Ubuntu system. Now execute the below command to install Node on Ubuntu using apt-get. This will also install NPM with node.js. This command also installs many other dependent packages on your system.

sudo apt install -y nodejs 

That’s it. This will install Node.js on your Ubuntu system.

Step 3 – Check Node.js and NPM Version

After installing node.js verify and check the installed version. You can find more details about the current version on node.js official website.

node -v

v19.2.0

Also, check the npm version

npm -v 

8.19.3

Step 4 – Create Demo Web Server (Optional)

This is an optional step. Suppose you want to test your node.js install. Let’s create a web server with “Hello World!” text. Create a file server.js

sudo nano server.js 

and add the following content

server.js
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(3000, "127.0.0.1"); console.log('Server running at http://127.0.0.1:3000/');

Save the file and close. Then start the Node application using the following command.

node server.js 

debugger listening on port 5858
Server running at http://127.0.0.1:3000/

You can also start the application with debugging enabled with the following commands.

node --inspect server.js

Debugger listening on ws://127.0.0.1:9229/938cf97a-a9e6-4672-922d-a22479ce4e29
For help, see: https://nodejs.org/en/docs/inspector
Server running at http://127.0.0.1:3000/

The web server has been started on port 3000. Now access http://127.0.0.1:3000/ URL in browser. Now you will need to configure a front-end server for your app.

Conclusion

In conclusion, we have seen how to install Node.js on Ubuntu and its derivatives via a new official PPA repository. This makes it easy for us to get started with Node.js development on our Linux systems. We can also use this repository to keep our installations up-to-date with the latest stable versions of Node.js. Be sure to check out other tutorials on our website for more tips and tricks about using Node.js!

The post How to Install Latest Node.js on Ubuntu appeared first on TecAdmin.

]]>
https://tecadmin.net/install-latest-nodejs-npm-on-ubuntu/feed/ 55
How To Install NVM on Ubuntu 22.04 https://tecadmin.net/how-to-install-nvm-on-ubuntu-22-04/ https://tecadmin.net/how-to-install-nvm-on-ubuntu-22-04/#respond Thu, 07 Apr 2022 02:02:25 +0000 https://tecadmin.net/?p=28843 NVM is a Node Version Manager tool. Using the NVM utility, you can install multiple node.js versions on a single system. You can also choose a specific Node version for applications. It also provides an option to auto-select the node version using the .nvmrc configuration file. In this tutorial, we will help you to install [...]

The post How To Install NVM on Ubuntu 22.04 appeared first on TecAdmin.

]]>
NVM is a Node Version Manager tool. Using the NVM utility, you can install multiple node.js versions on a single system. You can also choose a specific Node version for applications. It also provides an option to auto-select the node version using the .nvmrc configuration file.

In this tutorial, we will help you to install NVM on Ubuntu 22.04 Linux system. Also, provide you with the instructions to install multiple Node.js versions with useful examples.

Prerequisites

  • You must have a running Ubuntu 22.04 Linux system with shell access.
  • Log in with a user account to which you need to install node.js.

Installing NVM on Ubuntu

A shell script is available for the installation of nvm on the Ubuntu 22.04 (Jammy Jellyfish) Linux system. Open a terminal on your system or connect a remote system using SSH. Use the following commands to install curl on your system, then run the nvm installer script.

sudo apt install curl 
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash 

The nvm installer script creates an environment entry to the login script of the current user. You can either log out and log in again to load the environment or execute the below command to do the same.

source ~/.profile 

Installing Node using NVM

You can install any number of node.js versions of your requirements using nvm. Then you can use the required version for your application from installed node.js.

  • Install the latest version of node.js. Here node is the alias for the latest version.
    nvm install node 
    
  • To install a specific version of node:
    nvm install 16.14.0  
    

You can choose any other version to install using the above command. The very first version installed becomes the default. New shells will start with the default version of the node (e.g., nvm alias default).

Working with NVM

You can use the following command to list installed versions of the node for the current user.

nvm ls 

List available node.js versions for the installation.

nvm ls-remote 

You can also select a different version for the current session. The selected version will be the currently active version for the current shell only.

nvm use 16.14.0 

To find the default Node version set for the current user, type:

nvm run default --version 

You can run a Node script with the desired version of node.js using the below command:

nvm exec 16.14.0 server.js 

Conclusion

In this tutorial, you have learned to install nvm on Ubuntu 22.04 LTS (Jammy Jellyfish) Linux system. Also, get a basic understanding of the nvm uses.

The post How To Install NVM on Ubuntu 22.04 appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-install-nvm-on-ubuntu-22-04/feed/ 0
How To Install Node.Js on Debian 11 https://tecadmin.net/how-to-install-node-js-on-debian-11/ https://tecadmin.net/how-to-install-node-js-on-debian-11/#respond Sun, 19 Sep 2021 06:45:02 +0000 https://tecadmin.net/?p=27794 NodeJs is a JavaScript framework that allows users to easily develop autonomous network applications for general-purpose programming. NodeJs is free to make web application development more uniform and integrated through the use of JavaScript on both the front and back ends. It is available for all Operating Systems; in this article, you will learn how [...]

The post How To Install Node.Js on Debian 11 appeared first on TecAdmin.

]]>
NodeJs is a JavaScript framework that allows users to easily develop autonomous network applications for general-purpose programming. NodeJs is free to make web application development more uniform and integrated through the use of JavaScript on both the front and back ends.

It is available for all Operating Systems; in this article, you will learn how to install NodeJs on your Debian system (Linux OS) so that you can build amazing applications using NodeJs.

Given below are three methods to install NodeJs on Debian 11, you can follow any of these you find easier for successful installation:

Method 1 – Installing Nodejs from Debian Repository

At the time of writing this tutorial, the Node.js 12.22.5 version is available under default repositories. To get this version of NodeJs on your Debian system follow the steps mentioned below:

  1. Update Packages – First update all the packages previously installed in the System by below mentioned command:
    sudo apt update 
    
  2. Install Nodejs and NPM – The “npm” is the package manager of NodeJs, run the below mentioned command to install NodeJs and npm on Debian 11:
    sudo apt install nodejs npm 
    
  3. Check Version – To verify the correct version installation of NodeJs, run the below mentioned command to check version number of recently installed NodeJs:
    node -v 
    
    Output:
    v12.22.5

Method 2 – How to install NodeJs using NodeSource PPA

You can use a PPA (Personal Package Archive) provided by NodeSource to operate with the latest version of NodeJs. This is an alternative repository containing ‘Apt’ and contains current versions than the official Debian repositories for NodeJs.

Follow the steps below for successful installation of NodeJs using PPA:

  1. Install PPA – To install NodeJs Package using “Apt”, add the repository to Package list using below-mentioned syntax:

    curl -sL https://deb.nodesource.com/setup_[version_number] -o nodesource_setup.sh

    You can replace “version number” with the version you want to install, here I am installing stable version “16.x” by below mentioned command:

    curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh 
    
  2. Configure NodeSource setup – Run the below mentioned to inquire newly downloaded script, it will open a file and after inspecting the file press Ctrl+X to exit the file and return to terminal:
    nano nodesource_setup.sh 
    
  3. Run the Script – After configuring the script, run the script using below mentioned command:
    sudo bash nodesource_setup.sh 
    

    The PPA is added to your settings and the local package cache is instantly updated.

  4. Install NodeJs – Now after adding PPA, install NodeJs using below mentioned command, we don’t need to install npm separately here as it is already included in package:
    sudo apt install nodejs 
    
  5. Check Version – Now verify installation by checking version number of NodeJs:
    node -v 
    
    Output:
    v16.14.0

    Also check version of npm to verify its installation with NodeJs:

    npm -v 
    
    Output:
    8.3.1
  6. Installing “build-essential” – To get the needy tools to work with npm package, run the below mentioned command:
    sudo apt install build-essential 
    

Method 3 – Installing NodeJs using NVM on Debian 11

Node Version Manager, abbreviated as NVM, can also be used to install NodeJs on Debian. Instead of functioning in the operating system, NVM operates in the home directory of your user at the level of an independent directory. In other words, without impacting the overall system, you may install numerous autonomous NodeJs versions.
You may use NVM to control your environment while maintaining and handling prior releases in the latest NodeJs versions.

Follow the steps given below to install NodeJs using NVM:

  1. Download NVM installation script – Firstly, from the GitHub link download the nvm installation script by the below-mentioned command:
    curl -sL https://raw.githubusercontent.com/creationix/nvm/master/install.sh -o install_nvm.sh 
    
  2. Configure script – Using nano command, inquire the downloaded script by below mentioned command:
    nano install_nvm.sh 
    

    After checking the file, if everything seems good then exit the editor by pressing Ctrl+X.

  3. Run the script – After configuring the file, run the downloaded script:
    bash install_nvm.sh 
    
  4. Gain Access to NVM Functionality – Running NVM script will add additional setup to “~/ .profile” , allowing the new program, you will either log out or log in back; reload “~/ .profile” file using:
    source ~/.profile 
    
  5. Install NodeJs from available versions on NVM –
    First, we can check which versions of NodeJs are available on NVM by below mentioned command:

    nvm ls-remote 
    

    Now choose the version number you want to install from list, Syntax: nvm install [version-number]

    I am going to install version 16.14.0, so replace [version-number] with 16.14.0:

    nvm install 16.14.0 
    

    In general, the latest version is used by nvm, you need to tell nvm to use the version you downloaded by below mentioned command:

    nvm use 16.14.0 
    
  6. Check Version – You can check the version of NodeJs installed using:
    node -v 
    
    Output:
    v16.14.0

    If you are having many node versions installed on your system, to check recently installed version, run the below mentioned command:

    nvm ls 
    
    Output:
    -> v16.14.0 system default -> 16.14.0 (-> v16.14.0) iojs -> N/A (default) unstable -> N/A (default) node -> stable (-> v16.14.0) (default) stable -> 16.14 (-> v16.14.0) (default) lts/* -> lts/gallium (-> v16.14.0) lts/argon -> v4.9.1 (-> N/A) lts/boron -> v6.17.1 (-> N/A) lts/carbon -> v8.17.0 (-> N/A) lts/dubnium -> v10.24.1 (-> N/A) lts/erbium -> v12.22.10 (-> N/A) lts/fermium -> v14.19.0 (-> N/A) lts/gallium -> v16.14.0

Set Default Version of NodeJs using NVM

If you want to set any version as default, type the below-mentioned syntax: nvm alias default [version-number]

I am going to default version v16.14.0 so replace [version-number] with v16.14.0:

nvm alias default 16.14.0 

Test NodeJs

We can check whether our installed NodeJs is working or not; make sample JavaScript file using nano command:

nano sample.js 

The file will be opened in the editor now enter the below-shown content in the file to print “Hello World” on Terminal. Press Ctrl+O to save file and press Ctrl+X to exit file:

const http = require(‘http’);
const hostname = ‘localhost’;
const port = 3000;

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

Now to start application run below mentioned command:

node sample.js 
Output:
Server running at http://localhost:3000

Run below mentioned command to test application on another terminal:

curl http://localhost:3000 

How to uninstall NodeJs from Debian 11 Bullseye

Depending on the version you wish to target, you can remove NodeJs with apt or NVM You will need to deal with the apt program on the system level to uninstall versions installed from the Debian repository or from PPA.
To uninstall any of version, run the below mentioned command:

sudo apt remove nodejs 

If you wanted to uninstall version of NodeJs installed from NVM, for that first check the current version of NodeJs installed by below mentioned command:

nvm current 

Then run the below-mentioned syntax to uninstall any specific version of NodeJs installed using NVM on your system:

nvm uninstall [version-number]

I am uninstalling current version of NodeJs, so first I need to deactivate NVM:

nvm deactivate 

Now run the command:

nvm uninstall 12.1.0 

Conclusion

NodeJs is a server-side framework to build JavaScript apps. It is used for both back-end and front-end programming. In this article, we discuss its installation on Debian 11 using three methods which are using Debian’s official Repository, through PPA Repository, and also through NVM and also discuss its testing and uninstallation from the system.

The post How To Install Node.Js on Debian 11 appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-install-node-js-on-debian-11/feed/ 0
How To Install NVM on Debian 11 https://tecadmin.net/how-to-install-nvm-on-debian-11/ https://tecadmin.net/how-to-install-nvm-on-debian-11/#respond Mon, 30 Aug 2021 16:12:01 +0000 https://tecadmin.net/?p=23084 NVM stands for Node Version Manager, which is a command-line utility for installing Node.js. It allows the programmers for installing Node.js in their account only. This means the installation is done user-specific. All the users in a single system have their own installation of Node.js. Using the nvm utility, we can install the multiple node.js [...]

The post How To Install NVM on Debian 11 appeared first on TecAdmin.

]]>
NVM stands for Node Version Manager, which is a command-line utility for installing Node.js. It allows the programmers for installing Node.js in their account only. This means the installation is done user-specific. All the users in a single system have their own installation of Node.js.

Using the nvm utility, we can install the multiple node.js versions in a single account and manage them easily. The application can have use .nvmrc at root folder to autoselect the Node.js version.

This tutorial will help you to install nvm on Debian 11 “bullseye” Linux system.

Prerequisites

  • Assuming that you have a running Debian 11 Bullseye Linux system with shell access. No need to have sudo access.
  • Login to the system and open a shell in your account
  • The newly installed system are requested to complete initial server setup on Debian 11.

How to Install NVM on Debian 11

A shell script is available for the NVM installation on any Linux system. First of all, check if your system has installed the curl command-line utility. If not, use the following command to install curl.

sudo apt install curl -y 

Then execute the NVM installation bash script as your user. No need to use sudo with the installation script.

curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash 
Step to Install and Configure NVM on Debian 11

The above script makes all the required environment settings to the login script of the currently logged-in user. To apply the settings log out and log in again to your account or just execute the below command to do the same.

source ~/.bashrc

How to Install Node.js on Debian 11

The nvm allows you to install multiple Node.js versions for a single user account. Use the following commands to install the required node.js version on your Debian 11 system.

  • Install Latest Node Version – This is the most recent version released for the installation by Node.js team. You can use “node” as alias for the latest version.
    nvm install node 
    

    Installing Node.js with NVM
  • Installing Latest Stable Node Version – Use the --lts option with command line to install latest LTS (Long Term Release) version.
    nvm install node --lts 
    
  • To install a specific version of node:
    nvm install 12.20.1  
    

    Change 12.20.1 with your required Node.js version to install on Debian 11 system.

The very first version installed becomes the default. New shells will start with the default version of node (e.g., nvm alias default).

How to Use NVM?

Here are some useful options to use with the nvm command-line utility.

You can use the following command to list installed versions of Node for the current user.

nvm ls 

With this command, you can find the available Node.js version for the installation.

nvm ls-remote 

You can also select a different version for the current session. This will be a current active version for the current shell only.

nvm use 12.20.1 

To find the default Node version set for the current user, type:

nvm run default --version 

You can run a Node script with the desired version of node.js using belwo command:

nvm exec 12.20.1 server.js 

Conclusion

This tutorial helped you to install nvm on Debian 11 Bullseye Linux system. Additionally provided you the basic instructions to use the NVM utility.

The post How To Install NVM on Debian 11 appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-install-nvm-on-debian-11/feed/ 0
How To Use Environment Variables in Node.js https://tecadmin.net/how-to-use-environment-variables-in-nodejs/ https://tecadmin.net/how-to-use-environment-variables-in-nodejs/#respond Sat, 03 Jul 2021 03:31:31 +0000 https://tecadmin.net/?p=26467 Instead of defining the variables directly, you can use Environmental variables in node.js. You can use the Environmental variable anytime when you want to change the value depending on the environment. There are various use cases here. If you start using the environmental variable, you won’t face issues where the client says “It doesn’t work [...]

The post How To Use Environment Variables in Node.js appeared first on TecAdmin.

]]>
Instead of defining the variables directly, you can use Environmental variables in node.js. You can use the Environmental variable anytime when you want to change the value depending on the environment. There are various use cases here.

If you start using the environmental variable, you won’t face issues where the client says “It doesn’t work in my system”. This guide will cover all the things you should know about defining the Environmental variables and how you can use them in node.js. It has a lot to do with the .env file a well as with server.js. So, let’s begin the steps and see the steps.

Please read the code as you will have to enter some of the information such as key, port number, etc. We have mentioned it in the code itself and if possible, we have also added the comments.

Step 1 – Preparation

At first, you will have to set the port. Here is the code you can use.

// server.js
const port = process.env.PORT;
console.log(`Your port is ${port}`);

This code will go in the server.js file. You will have to create a file with the same name.
Thereafter, you also need to create the .env file. As of now, you don’t need to add anything to the env file.
You can do it by the command line. Just enter the name of the variable and then you can use the “=” sign for the value.

Here is an example of the same.

PORT=8626 node server.js 

Define Port at Runtime Environment in Nodejs

In the same way, if you want to pass two variables, you can see the below given example.

PORT=8626 NODE_ENV=development node server.js 

Now, this was how you can do the procedure using the command line. People don’t use the command line because there could be typing mistakes and it’s too complicated.

We will now focus on the .env file and do things from there.

You can add the following code in the env file.

NODE_ENV=development
PORT=8626
# Set your database/API connection information here
API_KEY=**************************
API_URL=**************************

Step 2 – Focus on .gitingore

Don’t forget about the .gitignore. You need to ensure that you have added the env file before you commit the changes.

One can simply press CMD + Shift + F and it will open the command prompt. You can enter “ignore” and then select the file you want to add.

Step 3 – Create package.json

You will first have to create a package.json. Run the code and it will then create a file for you with all the basic details.

npminit -y 

This file is needed to read the env file.

Step 4 – Install and edit env file

You can use the below code to install the env file.

npm install dotenv 

The above-mentioned line will fill the entry in the package.json that we created in the above step.

You can then replace the content of server.js with the following code.

// server.js
console.log(`Your port is ${process.env.PORT}`); // undefined
constdotenv = require('dotenv');
dotenv.config();
console.log(`Your port is ${process.env.PORT}`); // 8626

Step 5 – Find the Variables

You can run the code and find the variables with ease. We will again use the command line here. We will get the list from server.js.

node server.js 

You can define the variable now. To do that, you will have to create the variable in your .env file.

process.env.YOUR_ENV_VAR_GOES_HERE

It’s time to organize things manually. You can create a config.js file and add the code there.

// config.js
constdotenv = require('dotenv');
dotenv.config();
module.exports = {
endpoint: process.env.API_URL,
masterKey: process.env.API_KEY,
port: process.env.PORT
};

Once you do this, it’s time to modify the server.js file.

// server.js
const { port } = require('./config');
console.log(`Your port is ${port}`); // 8626

Define Port in .env in Nodejs

Define the constant in Config.js by adding the belw code.

const{ endpoint, masterKey, port } = require(‘./config’);

Step 6 – Reduce the Dependencies

It’s time to reduce the dependencies of the code. Nobody likes runtime dependencies. It’s not good in the long term. Luckily, there is a code through which you can remove the runtime dependencies in dotenv package.

You can load all the variables at first. This will decrease the time of execution. The next thing you can do here is to save the dependencies as dev dependencies. You can run the following line. This is where we will install dotenv and save it as dev. Here is the code for the same.

npm install dotenv --save-dev 

Thereafter, you can remove the code that has dependencies. This will also include the code from dotenv.config().

But wait, there exists a small problem. We were previously dependent on the .env file to load the variables. Now, we will preload all of them. The “- require (-r)” command will do the work.

You can also remove all the references.

node -r dotenv/config server.js 

The above-given code will be much useful in this.

As the code is preloaded, half of the work is done but there are still some of the things that need to be defined.

Step 7 – NPM Scripts

Put all the commands in the NPM script. This will make it easier to run and will give you a better loading time with fewer errors.

Here is the code you can have a look at.

scripts: {
"start_local": "node -r dotenv/config server.js"
}

Step 8 – NPM Extensions

It becomes hard to learn all the scripts. Therefore, you can use the extension. There is a great extension you can use here. It’s the npm extension. You can also use the npm script outline if you want.
This will make it easier to remember the lines.

Step 9 – Finalize

Now, it’s time to finalize all the things before you share them with the team. Check all the things before you send them to them.

Additionally, you can also use the .env.example to send the file.

# .env.example
NODE_ENV=development
PORT=8626
# DB information
API_KEY=your-core-api-key-goes-here

What we have done here is that we have created a template of the file. The template is very much useful when you are defining the environmental variables.

Final Words

To summarize, this is how you can start using environmental variables in your node.js. You can share it with your team and it will work smoothly. Whether you want to run in your system or your client’s system, there will be no issues. If you are using Docker like most of the pro developers do, the code will surely run there too. So, there will be no issues. You can easily run the code. What we recommend here is to add your logic and write a better code depending on your requirement.

The post How To Use Environment Variables in Node.js appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-use-environment-variables-in-nodejs/feed/ 0
How to Parse Command Line Arguments in Node.js https://tecadmin.net/how-to-parse-command-line-arguments-in-nodejs/ https://tecadmin.net/how-to-parse-command-line-arguments-in-nodejs/#respond Fri, 02 Jul 2021 03:05:24 +0000 https://tecadmin.net/?p=26434 Node.js is an event-based, open-source, and asynchronous I/O framework that uses Google’s V8 JavaScript engine. We use it to develop applications that use JavaScript both on the server and client sides. Node.js applications are written in JavaScript. Node.js applications also accept command-line arguments like any other programming language. By default, Node.js is able to handle [...]

The post How to Parse Command Line Arguments in Node.js appeared first on TecAdmin.

]]>
Node.js is an event-based, open-source, and asynchronous I/O framework that uses Google’s V8 JavaScript engine. We use it to develop applications that use JavaScript both on the server and client sides. Node.js applications are written in JavaScript.

Node.js applications also accept command-line arguments like any other programming language. By default, Node.js is able to handle your arguments but if you want some extra features then you can use third-party tools and packages like yargs and minimist. In this article, we will see how you can parse command line arguments in Node.js using process.argv, yargs, and minimist.

What are Command Line Arguments?

A command-line argument is a string of additional information or commands that are passed into a program while running it through the Command Line Interface(CLI) of an OS. These arguments usually include information used to set property or configuration values for an application.

In Node.js, all the command-line arguments given to the shell are forwarded to the process in an array called ‘argument values(argv).’ Later Node.js uses this array for every running process in the form of process.argv or you can say arguments are by default stored in the process.argv.

Why Use Command Line Arguments?

Command-line arguments are very flexible as they are passed as strings to your program and string data types can easily be converted to other types.

It allows you to pass information to an application before it starts and also you can pass an unlimited number of arguments through Command-Line.

What’s the example syntax of Command-Line Arguments?

Here is an example syntax, how the command line arguments look like:

 [runtime] [script_name] [argument-1 argument-2 argument-3 ... argument-n]

Arguments are separated by space and runtime could be anything like sh, java, node, etc.

How to Parse Command Line Arguments in Node.js

Here we will first see to parse arguments using process.argv and later with yargs and minimist.

1. Parse Arguments using process.argv

Using process.argv is the simplest way of parsing arguments in Node.js and you do not need to install any additional package or library for that. You just pass arguments to a Node.js application and these arguments are handled by process.argv by default.

There are three primary elements of process.argv array:

  • First, file system path pointing to the node executable.
  • Second the name of the JavaScript file that is being executed.
  • Third, the first argument that is passed by the user.

Example – We will write a simple Node script that will print all of the command line arguments passed to the application.

  • Create a file named ‘processargv.js’ and paste the following code.

    'use strict';
    for (let j = 0; j < process.argv.length; j++) {
        console.log(j + ' -> ' + (process.argv[j]));
    }

  • Now run ‘processargv.js’ using the following command by passing argument.
    node processargv.js I am Node 
    

    Here we are passing three arguments to the file and as a result, you will see that ‘I’, ‘am’, ‘Node’ is stored at the 2nd, 3rd, and 4th indexes respectively. And the output will look like this:

    Reading Node.js Command Arguments with Process.argv

2. Passing Arguments Using Yargs

Yargs is a Node.js module that can help you in passing arguments. It allows you to pass arguments in the form of key-value pairs and you can even access the argument values later in the program using the keys.

  • Install yargs module using this command.
    npm i yargs 
    
  • Now save the below code in a file named ‘yargs.js’ and while executing the program we will provide values for name and age.

    'use strict';
    
    const args = require('yargs').argv;
    
    console.log('Name: ' + args.name);
    console.log('Age: ' + args.age);

  • For executing the following command, execute the following code in your prompt. We are passing the values for name and age.
    node yargs.js --name=node --age=15 
    

    The output will look like this:

    Reading Node.js Command Arguments with Yargs Module

To understand more advanced features of yargs visit this advanced guide.

3. Parsing arguments using Minimist module

Another way of parsing command-line arguments to the Node.js applications is by using the minimist module. It parses arguments from the process.argv array and then transfers it into an easy-to-use associative array. This associative array can be used to access the elements using index names.

  • Install the minimist module by using this command.
    npm i minimist 
    
  • Now save the following script named ‘minimist.js’. Here we are using the slice method which will remove all prior array elements starting from the index passed to it as the parameter.

    'use strict';
    
    const args = require('minimist')(process.argv.slice(2));
    
    console.log(args.i);
    console.log(args.n);

  • While passing the argument we can also specify the character by which we want to access the elements. Here we will specify ‘i’ as the name for the second index and then ‘n’ as the name for the third index. Like this:
    node minimist.js –i node –n 15 
    

    The output will look like this:

    Reading Node.js Command Arguments with Minimist Module

Though minimist has not as many rich features as yargs still you can use it to make your work easy. For more detailed information about minimist visit here.

Conclusion

Argument parsing is a simple and important topic if you work on Node.js. There are multiple options available to make your work easy. So choose according to your needs if you want rich and advanced features then go with yargs otherwise choose from the process.argv and minimist.

The post How to Parse Command Line Arguments in Node.js appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-parse-command-line-arguments-in-nodejs/feed/ 0
How To Install Older Version of a NPM Package https://tecadmin.net/install-older-version-npm-package/ https://tecadmin.net/install-older-version-npm-package/#respond Sat, 26 Jun 2021 10:36:25 +0000 https://tecadmin.net/?p=26367 NPM (Node Package Manager) is a command-line tool for managing node modules for Node.js applications. It is used to install, update or delete a node module in your system. It also follows the pacakge.json file for proper management of node modules for an application. The npmjs.com is the centralized repository containing all the node.js modules. [...]

The post How To Install Older Version of a NPM Package appeared first on TecAdmin.

]]>
NPM (Node Package Manager) is a command-line tool for managing node modules for Node.js applications. It is used to install, update or delete a node module in your system. It also follows the pacakge.json file for proper management of node modules for an application.

The npmjs.com is the centralized repository containing all the node.js modules. Npm download the packages from npmjs and install them on a client machine. By default, NPM installs the latest version of an available module, but sometimes you may be required an older version of the module for your application.

This tutorial helps you for installing the old version of modules with NPM command-line tool.

Syntax

The npm specific version installation uses the following syntax:

npm install [packagename]@[version]

Here pacakgename is the name of the packages and version is the version number to be install.

Installing Specific Version Node Module

The default NPM installs the latest version of the package. But you can specify the version number to install the specific version of a Node.js package.

For example, to install the cowsay package with version 1.1.0, type:

npm install cowsay@1.1.0 
Installing Specific Version Node Module
Installing Specific Version Node Module

Similarly, you can install any node modules with the specific version, but the condition is that all the required dependencies are available on the module.

Search Available Package Version’s with NPM

Use the following command to find out all the available versions for a Node.js module. This will show you all the versions from the first version to the current version of the module.

npm view cowsay versions 

Output:

[
  '1.0.0', '1.0.1', '1.0.2',
  '1.0.3', '1.1.0', '1.1.1',
  '1.1.2', '1.1.3', '1.1.4',
  '1.1.5', '1.1.6', '1.1.7',
  '1.1.8', '1.1.9', '1.2.0',
  '1.2.1', '1.3.0', '1.3.1',
  '1.4.0', '1.5.0'
]

Conclusion

This tutorial describes the instructions to install an older version of node.js modules. Alternatively, you can say to install any specific version of node.js modules.

The post How To Install Older Version of a NPM Package appeared first on TecAdmin.

]]>
https://tecadmin.net/install-older-version-npm-package/feed/ 0
How to Install Node.js on Ubuntu 22.10 & 21.10 https://tecadmin.net/install-nodejs-ubuntu-non-lts/ https://tecadmin.net/install-nodejs-ubuntu-non-lts/#comments Wed, 02 Dec 2020 05:25:01 +0000 https://tecadmin.net/?p=23735 Node.js is the popular language for front-end programming. A number of JavaScript frameworks are available for quick-build mobile and web application development. NVM is a Node Version Manager tool. Using the NVM utility, you can install multiple node.js versions on a single system. You can also choose a specific Node version for applications. This tutorial [...]

The post How to Install Node.js on Ubuntu 22.10 & 21.10 appeared first on TecAdmin.

]]>
Node.js is the popular language for front-end programming. A number of JavaScript frameworks are available for quick-build mobile and web application development.

NVM is a Node Version Manager tool. Using the NVM utility, you can install multiple node.js versions on a single system. You can also choose a specific Node version for applications.

This tutorial described how to install node.js on Ubuntu 22.10 and 21.10 systems using NVM.

Prerequisites

  • A running Ubuntu Linux system with shell access.
  • Log in with a user account to which you need to install node.js.

Step 1 – Install NVM

A shell script is available for the installation of nvm on the Ubuntu system. Use the following commands to install curl on your system, then run the nvm installer script.

Open a terminal on your system and execute:

sudo apt install curl 
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash 

The script will create the necessary environment variables in the login script of the current user. You can either log out and log in again to load the environment or use the following to load the environment.

source ~/.profile   

Step 2 – Install Node.js on Ubuntu

The NVM allows you to install and manage multiple node.js versions for each user account on a Linux system. You can easily switch to the specific version anytime.

  1. To install the latest node.js version, type:
    nvm install node 
    
  2. To install the latest LTS version of node, type:
    nvm install lts  
    
  3. To install a specific version of node, type:
    nvm install 16.4.0  
    

    You can choose any other version to install using the above command.

The very first version installed becomes the default. New shells will start with the default version of the node (e.g., nvm alias default).

Step 3 – Other Useful commands

You can use the following command to list installed versions of the node for the current user.

nvm ls 

With this command, you can find the available node.js version for the installation.

nvm ls-remote 

You can also select a different version for the current session. The selected version will be the currently active version for the current shell only.

nvm use 16.14.0 

To find the default Node version set for the current user, type:

nvm run default --version 

You can run a Node script with the desired version of node.js using the below command:

nvm exec 16.14.0 server.js 

Conclusion

This tutorial described you to install node.js on Ubuntu 22.10, and 21.10 Linux systems using Node Version Manager.

The post How to Install Node.js on Ubuntu 22.10 & 21.10 appeared first on TecAdmin.

]]>
https://tecadmin.net/install-nodejs-ubuntu-non-lts/feed/ 1