1

I am trying to understand as how to make a local module. At the root of node application, I have a directory named lib. Inside the lib directory I have a .js file which looks like:

var Test = function() {
    return {
        say : function() {
            console.log('Good morning!');
        }
    }
}();

module.exports = Test;

I have modified my package.json with an entry of the path to the local module:

"dependencies": {
   "chat-service": "^0.13.1",
   "greet-module": "file:lib/Test"
}

Now, if I try to run a test script like:

var greet = require('greet-module');

console.log(greet.say());

it throws an error saying:

Error: Cannot find module 'greet-module'

What mistake am I making here?

helloJSON
  • 1,389
  • 3
  • 10
  • 10

1 Answers1

2

modules.export is incorrect. It should be module.exports with an s.

Also, make sure after you add the dependency to do an npm install. This will copy the file over to your node_modules and make it available to the require function.

See here for a good reference.

Update:

After going through some examples to figure this out I noticed, most projects have the structure I laid out below. You should probably format your local modules to be their own standalone packages. With their own folders and package.json files specifying their dependencies and name. Then you can include it with npm install -S lib/test.

It worked for me once I did it, and it'll be a good structure moving forward. Cheers.

enter image description here

See here for the code.

Community
  • 1
  • 1
matt
  • 1,680
  • 1
  • 13
  • 16
  • 1
    i think it should not be `modules.exports`, it should be `module.exports` – Mayank Shukla Feb 24 '17 at 03:21
  • @MayankShukla Thanks, fixed. I always screw it up. Try that again OP. – matt Feb 24 '17 at 03:22
  • @helloJSON See my addition. – matt Feb 24 '17 at 03:25
  • @matt When I run `npm install` it throws `ENOENT: no such file or directory, open '/home/roger/nodejs/test/lib/test'` error. Although, there exists a file named `test.js` inside `lib` folder. – helloJSON Feb 24 '17 at 03:36
  • Try adding .js to your filename in the dependency object. Doesn't look like node is adding in the `.js` extension for you. – matt Feb 24 '17 at 04:59
  • @helloJSON Sorry about all the troubleshooting, see my updated answer for a solution. Cheers. – matt Feb 24 '17 at 14:09