Every Node.js developer knows that when creating a new Node project, one of the very first things you’ll do is type npm init
and answer couple questions, and then install dependencies
and devDependencies
.
npm has specific definitions of packages and modules, which are easy to mix up. I’ll like to discuss these definitions and explain certain default files.
Generally, most npm packages are modules. However, there’s no requirement that an npm package should be a module. There are CLI packages, that contain only executable command-line interface(CLI) and don’t provide a main field to be loaded with require(), these type of package is not a module.
In the context of a Node program, the module is loaded from a file. For example, in the following program:
var acronym = require('acronym');
we can say that “variable acronym refers to the acronym module”.
Important words
are highlighted.. . .
.This project requires a fair understanding of Javascript Promises and Callbacks and Node.js v6.11.0 LTS or higher to support some ECMAScript 2015 features. You can follow this tutorial or view the full code for this tutorial on Github.
Now that you have completed the prerequisites, let’s start!
npm init
or npm init --yes
, if you’re feeling lazy. It will ask you to create your package.json file.
$ mkdir acronym && cd acronym $ npm init --yes
{
"name": "acronym",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
main
field will get created. The main field is a module ID, the entry point (main script) to your program. That is, if a user installs this package, and then does require("acronym")
, the main module exports object will be returned.Your Name
(email is optional): {
"name": "acronym",
"version": "1.0.0",
"description": "Transform sentences to acronyms.",
"main": "index.js",
"author": "Akinjide Bankole " // optional
}
$ touch index.js
$ open . -a 'Sublime Text'
"use strict";
module.exports = function acronym(sentence, callback) {
}
module.exports
encapsulates and allows the acronym
function to be with other code. The acronym
function takes two parameter, a string data type e.g. "for your information"
and a callback function.
. . .
return new Promise((resolve, reject) => {
});
. . .
We define and return an instance of the Promise class. A Promise is an object which can be returned synchronously from an asynchronous function, it may be in one of 3 possible states: fulfilled
, rejected
, or pending
, and produces a single value some time in the future.
. . .
if (sentence.length === 0) {
reject('String, Please! e.g. "for your information"');
return callback('String, Please! e.g. "for your information"');
}
. . .
The if
statement checks for the length of the sentence parameter, if the condition is true, we reject with an error message (String, Please! e.g. "for your information"
). The return keyword before the callback, immediately breaks out of the function call, returning the callback function with an error message.
. . .
else if (typeof sentence === 'function') {
callback = sentence;
reject('¯\\_(ツ)_/¯');
return callback('¯\\_(ツ)_/¯');
}
. . .
The else if
statement checks if the user passes in a function as the first parameter instead of a string, if the condition is true, we assign the function to callback and reject with an error message (¯\\_(ツ)_/¯
).
. . .
else {
const words = sentence.split(' ');
const acronym = words.map((word) => word[0]);
. . .
}
The else
statement will be the default if none of the conditions above was satified. The first line, we .split
the sentence into an array ['for', 'your', 'information']
. The second line, we .map
and return an array, with the first character of each word ['f', 'y', 'i']
and assign to variable acronym
.
. . .
else {
. . .
resolve(acronym.join(''));
return callback(null, acronym.join(''));
}
We .join
and resolve the acronym
array, and return the callback function with null as error and the joined acronym
array.
So far we have created the package.json
, index.js
file. Let’s create a script file, open with Sublime Text (or Atom, VIM, WebStorm) and test our index.js
:
$ touch example.js
$ open example.js -a 'Sublime Text'
const acronym = require('./'); // require the `index.js` file from the same directory.
acronym('for your information', (err, resp) => {
if (err) {
console.log(err);
}
console.log(resp);
});
$ node example.js
# fyi
Working on a package and testing iteratively without having to continually rebuild or publish to npm registry has been a major concern to package authors. npm link
is an handy way of linking and testing packages locally before publishing.
npm link
basically links a package folder to the global node_modules
directory. Package linking is a two-step process. First, you’d npm link
the pacakge folder, creating a symlink in the global node_modules
.
$ cd ~//acronym
# go to the package directory
$ npm link
# create a global symlink
Next, in , `npm link acronym` creates a link from the globally installed `acronym` to the **node_modules** directory of the
.
$ cd ~//
# go to some other package directory.
$ npm link acronym
# link-install the acronym package
Now the node_modules directory should look like this:
├─ node_modules
│ ├─ acronym -> ../../.nvm/versions/node/v4.6.1/lib/node_modules/acronym
├─ package.json
With npm link, requiring the local project becomes easy and we publish to npm when we are entirely ready.
We’ve tested the module
locally, now we publish.
.gitignore
.As I mentioned, we’ll be publishing this package to the npm registry so that it can be installed by name. Before we publish make sure your acronym directory looks like this:
├─ acronym
│ ├─ index.js
│ ├─ example.js
│ ├─ package.json
As with every registry, you must have a user on npm registry. If you don’t have one, create it with npm adduser
or using npm site. If you’ve created using npm site, use npm login
to store the credentials.
Use npm whoami
to ensure that the credentials are stored.
$ npm whoami
# akinjide
Use npm publish
to publish the package. You should see the package information when you visit [https://npmjs.com/package/](https://npmjs.com/package/)
. Replace `` with the package name.
$ npm publish
# + acronym2@1.0.0
If you’d like to remove your package from the npm registry, use npm unpublish
to publish the package.
$ npm unpublish
# - acronym2@1.0.0
When you make changes to your code and want to update the package you’ll need to update the version of the package. Use npm version
, where `` is a sematic versioning release type patch, minor or major. After updating the version number, you’ll need to publish the package again, use npm publish
.
Congrats! You now know how to build a node module, make it a package and publish to the npm registry. Feel free to use the code above and contributions are welcome.
#node-js #npm