0

Considering this is the file structure of my working directory

|-- bower.json
|-- lib
|   |-- foo1.js
|   |-- foo2.js
|   `-- foo3.js
|-- node_modules
|   |-- body-parser
|   |-- bower
|   |-- express
|   `-- md5
|-- package.json
|-- runserver.sh
|-- server.js
`-- test

How am I supposed to load the third party library modules ( present in ./node_modules ) in my modules that I write in ./lib directory ?

2
  • 2
    require("body-parser"); this will at first check in your local node_modules, if not found it will check in global node_modules directory Commented Oct 21, 2015 at 4:17
  • Check out the usage in the readme for each of the packages but generally you would dom something like var express = require('express'); Commented Oct 21, 2015 at 4:20

1 Answer 1

1

Your requires are relative to the file doing the requiring. If your server.js needs to require something from ./lib/, then you do that:

// in ./server.js
var foo1 = require('./lib/foo1'); // file path: resolve relative to this file.

The exception is "npm installed" dependencies, which live in the node_modules dir, and don't require a file location, just a name:

// in ./server.js
var express = require('express'); // not a file path: find in node_modules

// in ./lib/foo1.js
var express = require('express'); // not a file path: find in node_modules

// in some hypothetical ./lib/extended/secondary/mixin/foo7.js
var express = require('express'); // not a file path: find in node_modules
Sign up to request clarification or add additional context in comments.

4 Comments

Considering I need to use npm installed dependencies in my modules ( foo1, foo2m foo3) . How is it done ?
You do what is in my answer? If you need to use an npm installed module in your ./lib/foo1.js file, or any other file anywhere in your project tree, you still just require it directly by name.
Will node look the parent directory ? Because my modules are one level lower to the hierarchy of the file structure
See answer and comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.