Node.js also has some functions of encapsulation, similar to C # class library, encapsulated into modules so easy to use, after installation with require () can introduce the call.
One, Node.js module encapsulation
1. Create a folder named Censorify
2. Create 3 files Censortext.js, Package.json, readme.md files under censorify
1), under Censortext.js, enter a function 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;
}
function Getcensoreworlds ()
{return
censoredworlds.concat (custormcensoredwords);
}
Exports.censor=censor;
Exports.addcensoreworld=addcensoreworld;
Exports.getcensoreworlds=getcensoreworlds;
2), in package to configure inventory information such as version name and main instruction.
{
"author": "Cuiyanwei", "
name": "Censority",
"version": "0.1.1",
"description": "Censors words out of text,
"main": "Censortext",
"dependencies": {
"Express": "Latest"
},
"Enginee": {
" Node ":" * "
}
}
3), the creation of the Readme.md file is mainly descriptive description
3. Create a wrapper module using the command line
Use the command line to navigate to the Censorify folder and then use the command NPM Pack encapsulation to generate the tgz file, which encapsulates a module.
Second, the use of packaging modules
There are two ways to use a packaged module: Publish to the NPM registry, use it locally, and record only the methods used locally.
1. Create a name Readwords folder
2. The command line navigates to the Readwords folder and then installs the modules that are already encapsulated, if it is the direct NPM install name that has been posted to the NPM registry, if it is in the local npm install tgz file path.
3. After the installation is completed, the Node_modules folder containing the Censority subfolder is generated under the Readwords folder
4. New Readwords.js file Test (note Code console, encapsulation module functions do not write the 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 command line node Readwords.js to invoke Readwords.js view results
The above is the entire content of this article, I hope to help you learn.