How to share code between node.js apps?

The npm documentation recommends using npm-link to create your own Node.js packages locally, and then making them available to other Node.js applications. It’s a simple four-step process.

A typical procedure would be to first create a package with the following structure:

  hello
  | index.js
  | package.json

A typical implementation of these files would be:

index.js

  exports.world = function() {
     return('Hello World');
  }

package.json

  {
    "name": "hello",
    "version": "0.0.1",
    "private": true,
    "main": "index.js",
    "dependencies": {
    },
    "engines": {
    "node": "v0.6.x"
    }
  }

“private:true” ensures that npm will refuse to publish the package. This is a way to prevent accidental publication of private packages.

Next, navigate to the root of your Node.js package folder and run npm link to link the package globally so it can be used in other applications.

To use this package in another application, e.g., “hello-world”, with the following directory structure:

 hello-world
 | app.js

Navigate to the hello-world folder and run:

 npm link hello

Now you can use it like any other npm package like so:

app.js

  var http = require('http');
  var hello = require('hello');

  var server = http.createServer(function(req, res) {
     res.writeHead(200);
     res.end(hello.world());
  });
  server.listen(8080);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)