Map over files in Directory

Say I have a directory of .res files each with its own unique implementation of a log function

// logs/Log1.res
let log = () => {
  Js.log("Hello World")
}
// logs/Log2.res
let log = () => {
  Js.log("Hello World")
}

How can I create an array of the files as modules so I can loop and access their respective log functions.

Similar to this in JS

const logs = [];
const logFiles = fs.readdirSync('./logs').filter(file => file.endsWith('.js'));

for (const file of logFiles) {
	const log = require(`./log/${file}`);
	logs.push(log.toJSON());
}
1 Like

I asked something similar in Dynamicaly import user-provided ReScript module .

Probably no practical way to do this, unless you really want it, and willing to do something complicated and fragile.

In your case, though. Something I would try is to write a script, that would scan the directory, and produce a .res file with content like this:

module type Log = {
  let log: unit => unit
}

let logImplementations: array<module(Log)> = [
  // composed by the script based on files' names
  module(Log1), 
  module(Log2)
]

Then, having this generated code, you can use it like so:

logImplementations->Js.Array2.forEach((module(Log)) => Log.log())