This is short note about fast creation, publishing & using Node.js module via using Command Line Interface.
- Use
npm init
to create package.json. - Run
npm install
to install dependency and save it to package.json.--save
When the code in the foo package does
require('bar')
, it will be loaded either foo/node_modules/bar or from core modules if it was installed as a global module via nmp install -g
command.
Node modules creation with CLI
Just to refresh the memory, here is how how we create & use Node module:
Creating the Node module:
- Make a new folder
mkdir <package>
- Create packaje.json by running
npm init
- Create the file that will be loaded when your module is required. index.js by default.
- Publish your module to npm by using
npm publish
Using the published package:
- Make a new directory outside of the project
mkdir <dir>
andcd
into it - Run
npm install <package>
- Create a my.js file which requires the package and calls the method
- Run
node my.js
to invoke the script.
Bash
mkdir my-app
cd my-app
npm install simple-get-json --save
vi my.js
~
~ var getJSON = require('simple-get-json');
~ getJSON('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1', function(data){
~ console.log(data);
~ });
~ // press Esc :wq to save and quit from Vim
node my.js
Output:
JSON
{ coord: { lon: -0.13, lat: 51.51 },
weather:
[ { id: 300,
main: 'Drizzle',
description: 'light intensity drizzle',
icon: '09d' } ],
base: 'stations',
main:
{ temp: 280.32,
pressure: 1012,
humidity: 81,
temp_min: 279.15,
temp_max: 281.15 },
visibility: 10000,
wind: { speed: 4.1, deg: 80 },
clouds: { all: 90 },
dt: 1485789600,
sys:
{ type: 1,
id: 5091,
message: 0.0103,
country: 'GB',
sunrise: 1485762037,
sunset: 1485794875 },
id: 2643743,
name: 'London',
cod: 200 }
This is very great article it's inspiring for so many people. Thank you for sharing such a great article.
ReplyDeleteNode JS Online training
Node JS training in Hyderabad