To create a Node.js Packaged Module, you need to create the functionality in JavaScript, define the package using a package.json
file, and then either publish it to the registry or package it for local use.
The following steps take you through the process of building a Node.js Packaged Module, using a module called censorify
that will accept text and replace certain words with asterisks:
1. Create a project folder named .../censorify
. This will be the root of the package.
2. Inside that folder, create a file named censortext.js
.
3. Add the code from Listing 3.1 to censortext.js
. Most of the code is just basic JavaScript, but note that lines 18–20 export the functions censor()
, addCensoredWord()
, and getCensoredWords()
. exports.censor
is required for Node.js applications using this module to have access to the censor()
function as well as the other two functions.
01 var censoredWords = ["sad", "bad", "mad"];
02 var customCensoredWords = [];
03 function censor(inStr) {
04 for (idx in censoredWords) {
05 inStr = inStr.replace(censoredWords[idx], "****");
06 }
07 for (idx in customCensoredWords) {
08 inStr = inStr.replace(customCensoredWords[idx], "****");
09 }
10 return inStr;
11 }
12 function addCensoredWord(word){
13 customCensoredWords.push(word);
14 }
15 function getCensoredWords(){
16 return censoredWords.concat(customCensoredWords);
17 }
18 exports.censor = censor;
19 exports.addCensoredWord = addCensoredWord;
20 exports.getCensoredWords = getCensoredWords;
4. You need a package.json
file that will be used to generate the Node.js Packaged Module, so create a package.json
file in the .../censorify
folder. Then add contents similar to Listing 3.2. Specifically, you need to add at least the name
, version
, and main
directives. The main
directive needs to be the name of the main JavaScript module that will be loaded—in this case censortext
. Note that the .js is not required; Node.js automatically searches for the .js extension.
01 {
02 "author": "Brad Dayley",
03 "name": "censorify",
04 "version": "0.1.1",
05 "description": "Censors words out of text",
06 "main": "censortext",
07 "dependencies": {},
08 "engines": {
09 "node": "*"
10 }
11 }
5. Create a file named README.md
in the .../censorify
folder. Place in this file any readme instructions you would like.
6. Navigate to the .../censorify
folder in a console window and execute the following command to build a local package module:
npm pack
The npm pack
command creates a censorify-0.1.1.tgz
file in the .../censorify
folder. This is your first Node.js Packaged Module.
3.138.134.188