Home > Article > Web Front-end > Node.js module encapsulation and usage_node.js
Node.js also has some functional encapsulation, similar to C# class libraries, which are encapsulated into modules for easy use. After installation, you can use require() to introduce calls.
1. Node.js module encapsulation
1. Create a folder named censorify
2. Create 3 files censortext.js, package.json, and README.md files under censorify
1). Enter a function under censortext.js that filters specific words and replaces them with asterisks.
var censoredWorlds=["sad","bad","mad"]; var custormCensoredWords=[]; function censor(inStr) { for(idx in censoredWorlds) { inStr=inStr.replace(censoredWorlds[idx],"****"); } for(idx in custormCensoredWords) { inStr=inStr.replace(custormCensoredWords[idx],"****"); } return inStr; } function addCensoreWorld(world) { custormCensoredWords.push(world); } function getCensoreWorlds() { return censoredWorlds.concat(custormCensoredWords); } exports.censor=censor; exports.addCensoreWorld=addCensoreWorld; exports.getCensoreWorlds=getCensoreWorlds;
2). Configure manifest information in the package, such as version name and main instruction, etc.
{ "author":"cuiyanwei", "name":"censority", "version":"0.1.1", "description":"Censors words out of text", "main":"censortext", "dependencies":{ "express":"latest" }, "enginee":{ "node":"*" } }
3). The created README.md file is mainly a description
3. Use the command line to create a package module
Use the command line to navigate to the censorify folder, and then use the command npm pack to package and generate a tgz file, thus encapsulating a module.
2. Use of encapsulated modules
There are two ways to use the encapsulated module: publishing to the NPM registry and using it locally. Only the local method is recorded here.
1. Create a folder named readwords
2. Navigate to the readwords folder on the command line, and then install the packaged module. If it is the direct npm install name that has been published to the NPM registry, if it is the local npm install tgz file path.
3. After the installation is completed, the node_modules folder containing the censority subfolder will be generated under the readwords folder
4. Create a new readwords.js file to test (pay attention to the code console and the function of the encapsulated module so that you don’t write it wrong)
var censor=require("censority"); console.log(censor.getCensoreWorlds()); console.log(censor.censor("Some very sad,bad and mad text")); censor.addCensoreWorld("gloomy"); console.log(censor.getCensoreWorlds()); console.log(censor.censor("A very goolmy day."));
5. Use
Use the command line node readwords.js to call readwords.js to view the results
The above is the entire content of this article, I hope it will be helpful to everyone’s study.