0

I have added a js Module called mongoUtil, which contains the code hereafter, following a suggestion found at this link.

 const MongoClient = require( 'mongodb' ).MongoClient;
 const url = "mongodb://localhost:27017";

 var _db;

 module.exports = {
  connectToServer: function(callback) {
   MongoClient.connect(url,  {useNewUrlParser: true}, function(err, client) {
    _db  = client.db('MyDB');
    return callback(err);
   });
  },

  getDb: function() {
   return _db;
  }
 };

I have furthermore used the following line in my app.js Module:

const mongoUtil = require('mongoUtil')

However, I am obtaining the following error while the 2 Modules are located in the same Directory:

Error: Cannot find module 'mongoUtil'

What am I missing?

user229044
  • 232,980
  • 40
  • 330
  • 338
JF0001
  • 819
  • 7
  • 30

3 Answers3

1

If you provide a module name to require it will search node_modules for it.

If you want to read a module from the current directory, you need to use the file path. This can be relative: require("./mongoUtil")

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

The exact documentation is here including a (rather long) pseudocode explanation of how the algorithm of locating a module works.

But in short, there are two basic ways of loading a module:

  • Using the name of an installed module (may be globally or locally installed), for example require('mongodb'). This would look for the (global or local) node_modules/mongodb folder.
  • Using a path (absolute or relative), for example require('./mongoUtil'). This would look for a file at the given path - if it's relative, then it is relative to the current file.

So, the solution is to use require('./mongoUtil') and not require('mongoUtil').

CherryDT
  • 25,571
  • 5
  • 49
  • 74
0

This will work:

const mongoUtil = require('./mongoUtil.js');

Or even just the following, since the extension is automatically resolved:

const mongoUtil = require('./mongoUtil');