0

I have a folder called myscripts in the same folder as my index.js,this myscript folder contains individual javascript files at least 100, the individual js files are just scripts with one function, the function return a string,how do I access the individual function outputs in index.js without importing them one by one?

rid
  • 54,159
  • 26
  • 138
  • 178
Jerry Joseph
  • 81
  • 1
  • 8
  • You can't? Maybe something with a wildcard, but I don't know enough about imports to be sure. – Jack Bashford Jun 03 '20 at 09:16
  • You can either use [`glob` and `require`](https://stackoverflow.com/a/28976201/1487756) or use an [intermediate file](https://stackoverflow.com/a/29722646/1487756) that exports all the files from your folder – Moritz Roessler Jun 03 '20 at 09:19

1 Answers1

0

You could write a little loader-function which reads the contents of the directory where all of your scripts are, then require each file in there and store the result in an object in order for you to be able to access it later under the scipt's file-name. Something like:

const fs = require('fs');
const path = require('path');

async function loader(dir) {
  const scriptContainer = {};
  const contents = await fs.promises.readdir(dir);
  for (file of contents) {
    scriptContainer[file.replace('.js', '')] = require(path.join(dir, file));
    // can be simply scriptContainer[file] = .. if you don't mind using indexer-access later: scriptConatiner["your-file.js"]();
  }
  return scriptContainer;
}

(async () => {
  const scriptContainer = await loader('path-to-your-directory');
  scriptContainer.fileNameOfScript();
})();
eol
  • 15,597
  • 4
  • 25
  • 43
  • Why are you replacing the .js extension? – Jerry Joseph Jun 03 '20 at 10:25
  • You don't have to, but in order to able able to access the loaded module under `scriptContainer` you'd then need to use indexing access: `scriptContainer["your-file.js"]()` instead of `scriptContainer.yourFile()`. – eol Jun 03 '20 at 10:29