- Understanding Node.js
- Installing Node.js
- Working with Node Packages
- Creating a Node.js Application
- Writing Data to the Console
- Summary
- Next
Creating a Node.js Application
Now you have enough information to jump into a Node.js project and get your feet wet. In this section, you create your own Node Packaged Module and then use that module as a library in a Node.js application.
The code in this exercise is kept to a minimum so that you can see exactly how to create a package, publish it, and then use it again.
Creating a Node.js Packaged Module
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 an example called censorify. The censorify module accepts text and then replaces certain words with asterisks:
Create a project folder named .../censorify. This is the root of the package.
Inside that folder, create a file named censortext.js.
Add the code from Listing 3.1 to censortext.js. Most of the code is just basic JavaScript; however, note that lines 18–20 export the functions censor(), addCensoredWord(), and getCensoredWords(). The exports.censor is required for Node.js applications using this module to have access to the censor() function as well as the other two.
Listing 3.1 censortext.js: Implementing a simple censor function and exporting it for other modules using the package
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;
Once the module code is completed, you need to create a package.json file that is used to generate the Node.js Packaged Module. Create a package.json file in the .../censorify folder. Then add contents similar to Listing 3.2. Specifically, you need to add the name, version, and main directives as a minimum. 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.
Listing 3.2 package.json: Defining the Node.js module
01 { 02 "author": "Brendan 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 }
Create a file named README.md in the .../censorify folder. You can put whatever read me instructions you want in this file.
Navigate to the .../censorify folder in a console window and run the npm pack command to build a local package module.
The npm pack command creates a censorify-0.1.1.tgz file in the .../censorify folder. This is your first Node.js Packaged Module.
Publishing a Node.js Packaged Module to the NPM Registry
In the previous section you created a local Node.js Packaged Module using the npm pack command. You can also publish that same module to the NPM repository at http://npmjs.com/.
When modules are published to the NPM registry, they are accessible to everyone using the NPM manager utility discussed earlier. This allows you to distribute your modules and applications to others more easily.
The following steps describe the process of publishing the module to the NPM registry. These steps assume that you have completed steps 1 through 5 from the previous section:
Create a public repository to contain the code for the module. Then push the contents of the .../censorify folder up to that location. The following is an example of a Github repository URL:
https://github.com/username/projectname/directoryName/ch03/censorify
Create an account at https://npmjs.org/signup.
Use the npm adduser command from a console prompt to add the user you created to the environment.
Type in the username, password, and email that you used to create the account in step 2.
Modify the package.json file to include the new repository information and any keywords that you want made available in the registry search as shown in lines 7–14 in Listing 3.3.
Listing 3.3 package.json: Defining the Node.js module that includes the repository and keywords information
01 { 02 "author": "Brad Dayley", 03 "name": "censorify", 04 "version": "0.1.1", 05 "description": "Censors words out of text", 06 "main": "censortext", 07 "repository": { 08 "type": "git", 09 //"url": "Enter your github url" 10 }, 11 "keywords": [ 12 "censor", 13 "words" 14 ], 15 "dependencies": {}, 16 "engines": { 17 "node": "*" 18 } 19 }
Publish the module using the following command from the .../censor folder in the console:
npm publish
Once the package has been published you can search for it on the NPM registry and use the npm install command to install it into your environment.
To remove a package from the registry make sure that you have added a user with rights to the module to the environment using npm adduser and then execute the following command:
npm unpublish <project name>
For example, the following command unpublishes the censorify module:
npm unpublish censorify
In some instances you cannot unpublish the module without using the --force option. This option forces the removal and deletion of the module from the registry. For example:
npm unpublish censorify --force
Using a Node.js Packaged Module in a Node.js Application
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 simple: All you need to do is install the NPM 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 located on the file system. For example:
require("censorify") require("./lib/utils.js")
The .js filename extension is optional. If it is omitted, Node.js searches for it.
The following steps take you through that process so you can see how easy it is:
Create a project folder named .../readwords.
From a console 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
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
Verify that a folder named node_modules is created along with a subfolder named censorify.
Create a file named .../readwords/readwords.js.
Add the contents shown in Listing 3.4 to the 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.
Listing 3.4 readwords.js: Loading the censorify module when displaying text
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."));
Run the readwords.js application using the node readwords.js command and view the output shown in the following code block. Notice that the censored words are replaced with **** and that the new censored word gloomy is added to the censorify module instance censor.
C:\nodeCode\ch03\readwords>node readwords [ 'sad', 'bad', 'mad' ] Some very *****, ***** and ***** text. [ 'sad', 'bad', 'mad', 'gloomy' ] A very *** day.