Writing Node.js Modules

There are crucial reasons to use JS modules such as Maintainability, Namespacing and Reusability, among others benefits.

I consider the hello greetings as a good start to understand how modules work. Write a module called hello.js to print a message that define the beginning of the hello.js module and to export a greeting by writing the reserved words module.exports. Then write a file called index.js to invoke the module required with its path. It can be a relative path as it is shown:Improving our hello.js module, it can accept any name to make a greeting:Names are accepted even though a number would have been instead of “Tux”. A common JS module validates information by checking the type of the parameter in a function. It can be written in the same hello.js file as follow:We are defining two modules in the hello.js file, one to print the greeting and the other module to validate the type of the name entered, in case we set the name as number 200, a message of “Please enter a valid name” is shown inmediately.

And because writing in all caps is considered to be shouting, we can create another module to convert the name in the message all in lowercase if the input was written in uppercase. Another file “lower.js” is used this time to export it into the index.js file:jsmodules2

About Julita Inca

Ingeniero de Sistemas UNAC, Magíster en Ciencias de la Computación PUCP, Magíster en Computación de Alto Rendimiento de la Universidad de Edimburgo, OPW GNOME 2011, Miembro de la GNOME Foundation desde el 2012, Embajadora Fedora Perú desde el 2012, ganadora del scholarship of the Linux Foundation 2012, experiencia como Admin Linux en GMD y Especialista IT en IBM, con certificaciones RHCE, RHCSA, AIX 6.1, AIX 7 Administrator e ITILv3. Experiencia académica en universidades como PUCP, USIL y UNI. Leader of LinuXatUNI Community, HPC Software Specialist at UKAEA, and reviewer of the Technological Magazine of ESPOL-RTE, and volunteering Linux training for MINSA Peru... a simple mortal, just like you!
This entry was posted in τεχνολογια :: Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s