Home > Enterprise >  Unable to import module in nodejs using ES6 Modules
Unable to import module in nodejs using ES6 Modules

Time:10-22

I have just started learning Node.js and i was trying to connect my application to MongoDB database. Here Server.js is my main file with just two line

import { connectMongoDB } from "./config/db";
connectMongoDB();

and i was trying to import my function connectMongoDB from file db.js, here is the content of db.js

import config from "config";
import mongoose from "mongoose";

const mongoDBUri = config.get("mongoDBUri");
export const connectMongoDB = async () => {
  try {
    await mongoose.connect(mongoDBUri, {
      useNewUrlParser: true,
    });
    console.log("MongoDB connected");
  } catch (error) {
    console.log(
      "[Error] MongoDB did not get connected due to issue "   error.message
    );
    process.exit(1);
  }
};

location of file seems correct to me enter image description here

I tried using require instead of import and it worked fine. Error thrown -

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\bisht\Project\DHH\dhh\config\db' imported from C:\Users\bisht\Project\DHH\dhh\server.js
[0] Did you mean to import ../config/db.js?
[0]     at finalizeResolution (internal/modules/esm/resolve.js:259:11)
[0]     at moduleResolve (internal/modules/esm/resolve.js:636:10)
[0]     at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:726:11)
[0]     at Loader.resolve (internal/modules/esm/loader.js:97:40)
[0]     at Loader.getModuleJob (internal/modules/esm/loader.js:243:28)
[0]     at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:47:40)
[0]     at link (internal/modules/esm/module_job.js:46:36) {
[0]   code: 'ERR_MODULE_NOT_FOUND'

CodePudding user response:

Did you try running that function in an async context?

For instance:

import { connectMongoDB } from "./config/db";
    
(async () => {
    await connectMongoDB();
})();

CodePudding user response:

There is a difference between module.exports and export take a look at: module.exports vs. export default in Node.js and ES6 At your db.js file, try to change the function exporting as below:

exports.connectMongoDB = async () => {
  try {
    await mongoose.connect(mongoDBUri, {
      useNewUrlParser: true,
    });
    console.log("MongoDB connected");
  } catch (error) {
    console.log(
      "[Error] MongoDB did not get connected due to issue "   error.message
    );
    process.exit(1);
  }
};

CodePudding user response:

i went through the documentation of Node and found out that when we are using ES6 to import modules then we need to define our file with extension ".mjs" instead of just ".js" and while importing the function i also mentioned the extension like this - import { connectMongoDB } from "./config/db.mjs"; and it worked fine

  • Related