Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
dynamically import class from file and use a function in it

i have this file ./src/commands/test.js:

export default class {
    run() {
        console.log('test!')
    }
}

i am trying to make a command that will get all commands in that folder and call their run function:

#! /usr/bin/env node

const fs = require('fs')
const folders = [
    './src/commands',
    //'./my_modules/diontron/unity/src/commands',
]

folders.forEach(folder => {
    fs.readdir(folder, (err, files) => {
        files.forEach(file => {
            if (file != 'index.js') {
                let commandClass = require(folder + '/' + file).default
                let command = new commandClass()

                command.run()
            }
        })
    })
})

this gives me the error:

Cannot find module './src/commands/test.js'
    

how do i dynamically go through all files in a folder, require/import them, and use the class function?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can do it with dynamic import() rather than require. Note that you'll need a package.json in src or src/commands with "type": "module" in it, since test.js uses ESM by Node.js uses CommonJS by default.

This works for me in that setup:

#! /usr/bin/env node

const fs = require("fs");
const folders = [
    "./src/commands",
    //"./my_modules/diontron/unity/src/commands",
];

folders.forEach(folder => {
    fs.readdir(folder, (err, files) => {
        files.forEach(file => {
            if (file != "index.js") {
                const modFile = folder + "/" + file;
                import(modFile)
                .then(({ default: commandClass }) => {
                    const command = new commandClass();
                    command.run();
                })
                .catch(error => {
                    console.log(`Failed to load module ${modFile}`);
                });
            }
        });
    });
});

Although that runs the code in parallel. If you want to run it in series (each waiting for the previous one to complete), you might do this (note the change from "fs" to "fs/promises" at the top):

#! /usr/bin/env node

const fs = require("fs/promises");
const folders = [
    "./src/commands",
    //"./my_modules/diontron/unity/src/commands",
];

(async () => {
    for (const folder of folders) {
        for (const folder of folders) {
            const files = await fs.readdir(folder);
            for (const file of files) {
                const { default: commandClass } = await import(folder + "/" + file);
                const command = new commandClass();
                command.run();
            }
        }
    }
})()
.catch(error => {
    console.error(error);
});

That relies on the script being run from the parent folder of the folders you're searching. If you want to use the current path instead, you should use process.cwd() to get it, then use that to resolve the folders:

#! /usr/bin/env node

const fs = require("fs");
const path = require("path"); // ***
const folders = [
    "./src/commands",
    //"./my_modules/diontron/unity/src/commands",
];

const currentDir = process.cwd(); // ***

folders.forEach(folder => {
    fs.readdir(folder, (err, files) => {
        const fullFolder = path.join(currentDir, folder); // ***
        files.forEach(file => {
            if (file != "index.js") {
                const modFile = fullFolder + "/" + file; // ***
                import(modFile)
                .then(({ default: commandClass }) => {
                    const command = new commandClass();
                    command.run();
                })
                .catch(error => {
                    console.log(`Failed to load module ${modFile}`);
                });
            }
        });
    });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!