Package Manager NPM
Common command-line options are
- Search: find the module package in the REPOSITORY;--NPM search Express
- Install: installs the package using a Package.json file in the repository or local location,--npm install eapress;npm install [email protected];npm install. /abc.tgz
- Install-g: install a package in a globally accessible location;--npm install-g express;
- Remove: Delete a module; npm remove Express
- Pack: encapsulates the module defined in a Package.json file into A. tgz file;--npm pack
- View: Show details of the MODULE;--NPM View Express
- Publish: publish the module defined in a Package.json file to the REGISTRY;--NPM publish
- Unpublish: Cancel the module you have PUBLISHED;--NPM unpublish mymodule
Using the Package.json file
All modules must contain a Package.json file in his root directory. He is a simple JSON file package that defines a module, including its dependencies. The Package.json file contains several instructions that tell the node manager how to handle the Module. For example:
{ "name": "my_module", "version": "0.1.0", "description": "a simple Node. js Module ", " dependencies ": { " Express ":" latest " }}
Create a Node. JS module encapsulation
- Create a project folder Named./censorify. This will be the directory for this Package.
- Create a file in the file named Censortext.js.
1 varcensoredwords=["sad", "bad", "mad"];2 varcustomcensoredwords=[];3 functioncensor (inStr) {4 for(idxinchCensoredwords) {5Instr=instr.replace (censoredwords[idx], "* * *");6 }7 for(idxinchCustomcensoredwords) {8Instr=instr.replace (customcensoredwords[idx], "* * *");9 }Ten returninStr; one } a - functionAddcensoredword (word) { - Customcensoredwords.push (word); the } - functiongetcensoredwords () { - returnCensoredwords.concat (customcensoredwords); - } + -Exports.censor=censor; +exports.addcensoredword=addcensoredword; aexports.getcensoredwords=getcensoredwords;
- Create a Package.json file in The./censorify folder.
1 { 2 "author": "zhouruxian", 3 "name": "censorify", 4 "version": "0.1.1", 5 "description": "hi", 6 "main": " Censortext ", 7 " dependencies ": {}, 8 " Engines ": { 9 "node": "*"ten }
- In the console navigate to the .../censorify folder to execute
NPM Pack
The NPM pack will generate the Censorify-0.1.1.tgz file in The./censorify folder.
Using the Node. JS wrapper module in a Node. JS program
- Create a project folder name .../readwords
- Under the console, go to the folder to perform NPM Install. /censorrify/censorify-0.1.1.tgz
- Create a file Named../readwords/readwords.js
1 var censor=require ("censorify"); 2 console.log (censor.getcensoredwords ()); 3 console.log (censor.censor ("Some very sad,badand mad Text.") )); 4 censor.addcensoredword ("gloomy"); 5 console.log (censor.getcensoredwords ()); 6 console.log (censor.censor ("a very gloomy day"));
- Execute command Node readwords.js
The results show that some strings have been replaced by "* * *".
At the beginning of Nodejs