Shailendra Shailendra - 6 months ago 49
Node.js Question

How to resolve “Cannot find module” (custom module) error in express.js

I have my user.js file inside controller directory and utility.js file inside service directory.

In user.js, I am trying to access utility.js as below.

var Utility = require('./service/utility');

var express = require('express');

var router = express.Router();

error thrown by node.js

Debugger listening on port 5858


throw err;

Error: Cannot find module './service/utility'

at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)


Are controller and service adjacent directories like this?

+- service/
|   +- utility.js
+- controller/
    +- user.js

Relative paths in require are processed as relative to the current module. So if your directories are laid out like that, you'll need to get the path relative to user.js:

var Utility = require("../service/utility");