Search code examples
javascriptnode.jsrequiremodule.exports

How to properly export and require from parent directory in Nodejs?


I am new to Nodejs and am stumped regarding exports. I have read a number of SO questions and various blog posts, but I am missing something related to module.exports and require statements. I have a server directory set up like this.

User/
|-- sqldb.js
|
|-- site1/
   |-- test.js
|
|-- site2/
   |-- foo.js
   |-- bar.js

sqldb.js is a module that manages a mysql pool of database connections, allowing the child sites to concurrently access the parent database.

--- sqldb.js ---

// ... code and stuff ... 

async function initDB(){
    console.log("Initializing database");
}

async function addPlayers(players) {
    console.log("Add Players: ", players);
}

module.exports = {
    initDB,
    addPlayers
}

In test.js I would like to require sqldb.js from the parent directory so I can call the addPlayers function.

--- test.js ---

const {sqldb} = require('../sqldb.js');

console.log("sqldb: ", sqldb);

var players = ['Bob', 'Samantha'];

sqldb.addPlayers(players);

Logging sqldb shows undefined and then calling addPlayers on it gives the expected TypeError: Cannot read property 'addPlayers' of undefined error.

Can anyone offer some insight on how to fix this?


Solution

  • using const {sqldb} = require('../sqldb.js'); specifies a named import. This works if your sqldb.js has got a method with name sqldb.

    Since you have default export in sqldb.js, you gotta use:

    Default Export:

    const sqldb = require('../sqldb.js')

    and to access addPlayers - use sqldb.addPlayers();

    Named Export:

    or you can also use named exports like:

    const {addPlayers,initDB} = require('../sqldb.js');

    then you can directly call addPlayers();

    Hope this helps!