Welcome to FindNerd. Today we are going to discuss the process for building the command-line tools for your application. If you are reading our blogs on daily basis then you must have a good command on nodejs. We have explained different modules available in nodejs or npm. If you did not read our blog till now then read these blogs first. Here we are going to take a small example. Please have a look.
// package.json
{
"name": "airlines",
"version": "1.0.0",
"description": "testing one",
"main": "index.js",
"dependencies": {
"express": "^4.14.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "deepak verma",
"license": "ISC"
}
Above file we set the dependencies for the application. In this we have mentioned the application name, version, description, main as first file to run, modules as dependencies and many more.
// index.js
var http = require('http'),
express = require('express');
var app = express().get('/',function(req,res){
res.end('go end');
});
http.createServer(app).listen(3000);
In above file we have loaded the express and http modules, created a simple get request and passed the message to the browser. In the end we have created server for listening.
If you want to run the application then you need to open the terminal, go to application folder and run below command
node index.js
Here we want to run this application differently and in minimum steps. We want to run application with application name and without point the application directory so our application name is airlines and we will run the application without going to application directory as well as without node command. Please have a look.
First of all you need to add below code in package.json file. You can paste this code above the dependencies in the file.
"bin": "./index.js",
After that you need to add below line of code in index.js file. You have to add this code in very first line.
#!/usr/bin/env node
Now go to application directory and run the below command. If you are getting any error then you can also add sudo in this command.
npm link
Now close the terminal and type airlines. After press enter server will start and you can access the application in browser.
application link : http://localhost:3000/
Thank you for being with us!
0 Comment(s)