How to create head command on node JS - A step-by-step guide
The cause for this weblog publish is to give an explanation for what prompted us to create a head command on node JS.
First, you must know about Nodejs -Node.js is an open-source server environment. It allows you to run JavaScript on the server.Node.js is a cross-platform environment and library for running JavaScript applications that are used to create networking and server-side applications. It also provides a rich library of various JavaScript modules to simplify the development of web applications.
- Install the package on nodejs
- pass the arguments of terminal
- Analysis of the website status
- Build the option lunch the website
Build the Node Project using this command: mkdir cli-project && cd CLI-project
Install a Node Project by using this command: npm init -y.
Build a Node Project with a package.json:
{
"name": "cli-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
}
Create a file index.js file
softwarequery index.js
Click this file and print "Hello, It is my first CLI tool" to the console
inside the index.js file - console.log("Hello, It is my first CLI tool")
Run the node index and back to the terminal
$ node index
Hello, It is my first CLI tool
Now that your node app is running, it's time to turn it into a shell command. To call our index.js file directly without the node command, enter this node #! / Usr / bin / env at the top of our index .js file
\\ index.js
#!/usr/bin/env node
console.log("Hello, It is my first CLI tool")
Then, add the bin attribute to the package.json file. However, our project runs in a single file, so we do not use the bin attribute to specify the command name
{
"name": "cli-project",
"version": "1.0.0",
// ...
"bin": "./index.js",
// ...
}
If you run cli-project from the project directory, it should come back now
$ cli-project
Hello, It is my first CLI tool
We're going to make two changes now. We don't want our CLI name to be a Cli project. Therefore we change the value of the property package.json name to webcheck.
{
"name": "webcheck",
// ...
}
Our shell commands are still local. It's time to turn to global. The Run
npm link
Navigates from the root directory of our project, and then runs webcheck from any directory. You should see results like this.
$ Webcheck,
Hello! It is my first CLI tool.
Congratulations! !!You just created your first Shell command using the host application.It can be sent to NPM for users to download and run. However, since we are only half of the project, it is recommended that you wait for the node application to complete before publishing.
Use the built-in Argv node module. According to the official documentation of nodejs, the process.argv property returns an array containing the command line parameters passed when starting the Node.js process.
The first element is process.execPath. The second element is the path of the running JavaScript file. The remaining elements are other command line parameters.Therefore, every parameter we pass to the terminal is the third element of the array. Edit your index.js file as shown below.
\\index.js/usr/bin/env nodeconsole.log (processs.argv);
Run your application in the terminal.The result should look like the following.
#$ Webcheck
[
C:\Program Files\nodejs\node.exe,
C:\Users\adeniyi\Desktop\Projects\cli-project\index
]
Now add an additional parameter in the command and output. It should look like this.
$ Web test file C:\Program Files\nodejs\node.exe,
C:\Users\adeniyi\Desktop\Projects\cli-project\index,
file note: The more parameters you add, the larger the array. For our purposes, we restrict the parameter to a string and parse it as the third element in the item array. Now it is time to analyze this parameter in our application. And get information from isitup api. Open the index.js file and put this code in.
#!/usr/bin/env node
const fetch = require("node-fetch");
// console.log(process.argv);
const website = process.argv[2];
function CheckWeb(name) {
const info =fetch(`https://isitup.org/${name}.json`)
.then(response => response.json());
info.then(function(result) {
if (result.response_code == 200) {
console.log('website is up and running')
} else {
console.log('website is down')
}
}
CheckWeb(website);
we need a -fetch node package to Help us get data from isitup API, because this node does not support native JavaScript search. Run npm install node-fetch.
Our CheckWeb function takes a name parameter and receives the corresponding response from the API. Now, we pass the command line parameters to the function. Let's go to the terminal and see what code is running.
$ Webcheck softwarequery.com
website is running!
$ webcheck bing.com
The page is down.
Wait so let's try to find out what is wrong here. My favorite debugging tool (console) for recovery.Then
#!/usr/bin/env node
//...
function CheckWeb(name) {
const info =fetch(`https://isitup.org/${name}.json`)
.then(response => response.json());
info.then(function(result) {
console.log(result)
}
CheckWeb(website);
run the application again from the terminal
#!/usr/bin/env node
$ webcheck google.com
{
domain: "bing.com",
port: 80,
status_code: 1,
response_ip: "217.62.432.206",
response_code: 301,
response_time: 0.010
}
We need to notify our application and tell us that Google is active. This can be done in two ways: generate a string of if else statements by searching for the appropriate response code or finding an empty response code.
#!/usr/bin/env node
const fetch = require("node-fetch");
// console.log(process.argv);
const website = process.argv[2];
function CheckWeb(name) {
const info =fetch(`https://isitup.org/${name}.json`)
.then(response => response.json());
info.then(function(result) {
if (result.response_code == null) {
console.log('website is down')
} else {
console.log('website is up and running')
}
}
CheckWeb(website);
$ webcheck bing.com
website is up and running
#!/usr/bin/env node
const fetch = require("node-fetch");
// console.log(process.argv);
const website = process.argv[2];
function CheckWeb(name) {
const info =fetch(`https://isitup.org/${name}.json`)
.then(response => response.json());
info.then(function(result) {
if (result.response_code == 200) {
console.log('\x1b[32m%s\x1b[0m', 'website is up and running');
} else if (result.response_code == 301) {
console.log('\x1b[34m%s\x1b[0m', 'website has been moved permanently but is up');
} else if (result.response_code == 302){
console.log('\x1b[34m%s\x1b[0m', 'temporary redirect, website is up');
} else if (result.response_code == 403) {
console.log('\x1b[33m%s\x1b[0m', 'information not found');
}
else {
console.log('\x1b[31m%s\x1b[0m', 'website is down')
}
});
CheckWeb(website);
$ webcheck google.com
website has been moved permanently but is up
Build a .npmignore file. print the file
//.npmignore
node_modules/
This ensures that you will not release any node modules with the package.
npm publish
Please log out npm and open new terminal npm login
if you want live the website using the terminal
First you need to open package and open a URL then we create a function and go to live the website
npm install open
open index,js file again
#!/usr/bin/env node
const fetch = require("node-fetch");
const open = require("open");
const website = process.argv[2];
function CheckWeb(name) {
const info =fetch(`https://isitup.org/${name}.json`)
.then(response => response.json());
info.then(function(result) {
function openWebSite () {
setTimeout(function()
{ open(`https://${result.domain}`); }, 1000);
};
if (result.response_code == 200) {
console.log('\x1b[32m%s\x1b[0m', 'website is up and running');
openWebSite();
} else if (result.response_code == 301) {
console.log('\x1b[32m%s\x1b[0m', 'website has been moved permanently but is up');
openWebSite();
} else if (result.response_code == 302){
console.log('\x1b[34m%s\x1b[0m', 'temporary redirect, website is up');
openWebSite();
} else if (result.response_code == 403) {
console.log('\x1b[33m%s\x1b[0m', 'information not found');
openWebSite();
}
else {
console.log('\x1b[31m%s\x1b[0m', 'website is down')
}
});
}
}
CheckWeb(website);
function is help to open a website and live the website.open a terminal shoot the command then chrome browser is automatically open. user have athurity to open a website or not. you should install a packages of args and inquirer.
npm install arg inquirer
#!/usr/bin/env node
const fetch = require("node-fetch");
const open = require('open');
const arg = require('arg');
const inquirer = require('inquirer');
function ParseCliArgsIntoOptions() {
const args = arg(
{
'--website': Boolean,
'--yes': Boolean,
'-w': '--website',
'-y': '--yes',
},
{
argv: process.argv.slice(2),
}
);
return {
website: args['--website'] || false,
};
}
async function PromptForOptions(options) {
const questions = [];
if (!options.website) {
questions.push({
type: 'confirm',
name: 'website',
message: 'Open the website on your browser?',
default: false,
});
}
const answers = await inquirer.prompt(questions);
return {
...options,
website: options.website || answers.website,
};
}
async function LaunchWebsite(result) {
let options = ParseCliArgsIntoOptions();
options = await PromptForOptions(options);
if (options.website == true) {
open(`https://${result.domain}`);
}
}
const website = process.argv[2];
function CheckWeb(name) {
// ....
}
Now website is live with the help of function and we are going to create a another function Parse CliArgsIntoOptions() and ParseCliArgsIntoOptions().if this condition is true then website is open . so we are going to using these function then live the website.
#!/usr/bin/env node
const fetch = require("node-fetch");
const open = require('open');
const arg = require('arg');
const inquirer = require('inquirer');
function ParseCliArgsIntoOptions() {
//...
}
async function PromptForOptions(options) {
//...
}
async function LaunchWebsite(result) {
//...
}
function CheckWeb(name) {
const info =fetch(`https://isitup.org/${name}.json`)
.then(response => response.json());
info.then(function(result) {
if (result.response_code == 200) {
console.log('\x1b[32m%s\x1b[0m', 'website is up and running');
LaunchWebsite(result)
} else if (result.response_code == 301) {
console.log('\x1b[32m%s\x1b[0m', 'website has been moved permanently but is up');
LaunchWebsite(result)
console.log('\x1b[34m%s\x1b[0m', 'website has been moved permanently but is up');
LaunchWebsite(result)
} else if (result.response_code == 302){
console.log('\x1b[34m%s\x1b[0m', 'temporary redirect, website is up');
LaunchWebsite(result)
} else if (result.response_code == 403) {
console.log('\x1b[33m%s\x1b[0m', 'information not found');
LaunchWebsite(result)
}
else {
console.log('\x1b[31m%s\x1b[0m', 'website is down')
}
});
}
}
CheckWeb(website);
Now your command is successfully executed then the result is here:
$ webcheck bing.com
website has been moved permanently but is up
? Open the website on your browser? (y/N)
Let us spherical off via way of means of managing mistakes for those who would possibly neglect to feature the internet site extension. The internet site is probably up however this can in reality go back it as down.
$ webcheck bing
website is down
There are many ways to achieve this goal. You can write, create an array containing all possible expansions , and write a regular expression function to find one of the array parameters in the string on our website. If you ask me, it is unnecessary. You can easily find the substring in our parameters like this.
#!/usr/bin/env node
const fetch = require("node-fetch");
const open = require('open');
const arg = require('arg');
const inquirer = require('inquirer');
function ParseCliArgsIntoOptions() {
//...
}
async function PromptForOptions(options) {
//...
}
async function LaunchWebsite(result) {
//...
}
function CheckWeb(name) {
if (name.indexOf('.') > -1) {
const info =fetch(`https://isitup.org/${name}.json`)
.then(response => response.json());
info.then(function(result) {
//...
});
} else {
console.log('\x1b[31m%s\x1b[0m', 'please append your url extension e.g(yandix.com)')
}
}
CheckWeb(website);
inside the terminal
$ webcheck google
please append your url extension e.g(yandix.com)
I think this post is very help for all programmer if it is good please comment it or if you want give any suggestion then write it.

Comments