In the previous sections, you learned how to create and publish a Node.js module. This section provides an example of actually using a Node.js module inside your Node.js applications. Node.js makes this extremely simple. All you need to do is install the module into your application structure and then use the require()
method to load the module.
The require()
method accepts either an installed module name or a path to a .js file that is located on the file system. For example:
require("censorify")
require("./lib/utils.js")
The .js filename extension is optional. If it is omitted, then Node.js will search for it.
Follow these steps to see how easy this process is:
1. Create a project folder name .../readwords
.
2. From a command prompt inside the .../readwords
folder, use the following command to install the censorify
module from the censorify-0.1.1.tgz
package you created earlier:
npm install ../censorify/censorify-0.1.1.tgz
3. Or, if you have published the censorify
module, you can use the standard command to download and install it from the NPM registry:
npm install censorify
4. Verify that a folder named node_modules
should be created, along with a subfolder named censorify
.
5. Create a file named .../readwords/readwords.js
.
6. Add the contents shown in Listing 3.4 to your new readwords.js
file. Notice that a require()
call loads the censorify
module and assigns it to the variable censor
. Then the censor
variable can be used to invoke the getCensoredWords()
, addCensoredWords()
, and censor()
functions from the censorify
module.
1 var censor = require("censorify");
2 console.log(censor.getCensoredWords());
3 console.log(censor.censor("Some very sad, bad and mad text."));
4 censor.addCensoredWord("gloomy");
5 console.log(censor.getCensoredWords());
6 console.log(censor.censor("A very gloomy day."));
7. Run the readwords.js
application, using the following command, and you should get the output shown in Figure 3.4:
node readwords.js
Notice that the censored words are replaced with ****
, and that the new censored word gloomy
is added to the censorify
module instance censor.
18.221.76.44