A Ruby Developer’s Guide to Creating Node Modules

Terminology

  • npm is Node/JavaScript’s version of bundler. It allows you to install packages/manage dependencies. $ npm install package-name
  • a package is something you can install with npm. It can include one or more modules within it
  • package.json. Similar to a gemspec. Describes the functionality of your package and lists all the dependencies.
  • You can use $ npm install package-name --save to add a dependency to your package.json (Like adding a gem to your gemfile or gemspec).
  • packages are hosted on npmjs.com. Equivalent of RubyGems
  • a module is a library you can use within your app. Anything that you can require is a module. var cats = require(‘cats’);. You can have multiple modules within a package. Having a single module within a package is also okay (and recommended)

Modules Should Do One Thing™

Naming Conventions

  • must be all-lower-case-separated-by-hyphens
  • must use URL friendly characters
  • have a max length is 214 characters
npm view i-want-this-name

Getting Started

Reminder: package.json is similar to a Ruby gem’s gemspec. It describes the package and all of its dependencies.

git clone https://github.com/you/your-new-repo.git
cd your-new-repo
npm init

Writing the module

index.js
package.json
README.md *
LICENSE *
// index.js
module.exports = function(a, b) {
return a + b;
}
var add = require('./index.js');
add(1,2)
// => 3
// index.js
module.exports = {
hello: 'Hello, world',
add(a,b) {
return a + b;
}
}
var myModule = require('./index.js');
myModule.hello
// => 'Hello, world'
myModule.add(1,2)
// => 3

Trying it out in a REPL

node REPL

Testing the module

npm install mocha --save-dev
npm install chai --save-dev
var expect = require(‘chai’).expect,
add = require(‘../index’);
describe(‘add’, function() {
it(‘adds two numbers together’, () => {
expect(add(1, 2)).to.eq(3);
});
});
mocha test
add
✓ adds two numbers together
1 passing (9ms)
“scripts”: {
“test”: “mocha test”
},

Travis CI

language: node_js
node_js:
— “4.2”
— “4.1”
— “4.0”

Publishing the module

npm set init.author.name "Your Name"
npm set init.author.email "you@email.com"
npm set init.author.url "http://website.com"

npm adduser
git tag 0.1.0
git push origin master --tags
npm publish

Learn More

code @ProductHunt. my little sister thinks i’m cool.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mike Coutermarsh

Mike Coutermarsh

code @ProductHunt. my little sister thinks i’m cool.

More from Medium

Tasker, React/Redux + Rails API Final Project

Node.js| An Explanatory Review

Why Should I Use Node.js?

Post to Sinatra with React JS/Ruby