0

I have some existing JS code which I am releasing as an NPM package. Let's call it "my-pkg". I've created the package.json and installed my new local package. My package consists of these files:

  • my-pkg.js
  • package.json

my-pkg.js

function ping() {
    console.log("Hi!");
}

package.json

{
  "name": "my-pkg",
  "version": "1.0.0",
  "description": "My test package.",
  "main": "my-pkg.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Me",
  "license": "ISC"
}

I try to use my package like this:

npm install .\my-pkg
node
> var myPkg = require("my-pkg");
undefined
> myPkg.ping();
TypeError: undefined is not a function

Note that this is on Windows 8 in an elevated command line with Node.JS v0.12.2. I am looking to expose existing JS functionality, not write a brand new NPM package. What am I missing here?

3
  • Show us some code. What do you have in my-pkg.js? Commented May 14, 2015 at 15:50
  • @E_net4 Too quick - just added code. :) Commented May 14, 2015 at 15:50
  • Writing a "brand new NPM package" literally takes a minute. You've basically done it by accident here. Commented May 14, 2015 at 15:52

1 Answer 1

4

All Node.js modules must export its contents via module.exports. You lack the following in your file:

module.exports.ping = ping;

This works as well (exports is initially assigned to module.exports):

exports.ping = ping;
Sign up to request clarification or add additional context in comments.

9 Comments

This has to be done for every exposed function, then? Can't just simply expose the contents of the "main" JS as-is? I'd have to add an index.js and it would simply wrap/point to the existing JS functions in my library, is this the correct way to go about it?
@JoshM. The whole point of module.exports is to control what's exposed and what's private. By default everything is private. There's no way to "export all", but you can declare all your functions in the context of an export if you prefer: module.exports = { ping: function() { ... } }.
It's the beauty of the Node.js module system. Everything you declare in a module is private unless you either export it or make it a global (which I do not recommend).
My library already handles what should be public/private, so I would only be exposing functions which are already public. That's why it seems redundant to me to wrap/point to functions which I've already determined to be "public", but I'm new to Node.JS so bare with me. I'll give it a go. Thanks!
@JoshM. I'd say it's much easier if you rely on Node's module system rather than making your own workarounds to attain encapsulation at this level.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.