0

I've got a folder in my node.js project that contains multiple files, which I'd like to execute via a script. The names of the files are numbers just like '001.js', '002.js' and the script is meant to execute them in that order (from small to big) one after the other (asynchronous).

Unfortunately I can't really figure out a way to get this done the easy way. Currently I'm importing all files into the script and execute them one after the other but I know that this isn't sustainable and kinda ridiculous...

Is there an easier way to achieve this result via a lean script?

Vickel
  • 7,879
  • 6
  • 35
  • 56
Architecd
  • 63
  • 1
  • 8
  • `require` them and execute them using one of their export functions. – Yousername Dec 28 '19 at 16:06
  • That's what I'm doing right now, which is quite a lot of manual code as every single file needs to be included in the script. Instead I'd like to send them all through a loop via a lean script. – Architecd Dec 28 '19 at 16:14

1 Answers1

0

This answer can help https://stackoverflow.com/a/2727191/829300

You can use 'fs' to read all files in a folder then require all. Once you have got the array of file you can sort it

const fs = require('fs');
const testFolder = './folder/';

fs.readdir(testFolder, (err, files) => {
    files.forEach(file => {
        var x = require(testFolder + file)
        console.log(x)
    });
});
Taymer
  • 304
  • 2
  • 7