Export Files as Modules

3.0.2 · active · verified Tue Apr 21

export-files is a Node.js utility designed to automatically export all JavaScript files within a specified directory as modules. It provides a simple mechanism to aggregate multiple source files into a single object, where each file's export becomes a property. The current stable version is 3.0.2, with previous major breaking changes noted in v3.0.0 and v0.2.0. A key differentiator is its exclusive focus on CommonJS `require` syntax, explicitly stating it does not support ES Module `import` statements. It offers robust features like recursive directory processing, file filtering, and customizable key casing for the exported modules, making it suitable for organizing larger Node.js projects into modular structures without manual `require` statements for every file.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `export-files` to load JavaScript modules from a directory, including nested directories, and access their exports. The example sets up a temporary directory with modules and cleans up afterwards.

const path = require('path');
const fs = require('fs');
const exportFiles = require('export-files');

// 1. Create a dummy directory and files for demonstration
const exampleDir = path.join(__dirname, 'temp_example_modules');
const nestedDir = path.join(exampleDir, 'nested');

if (!fs.existsSync(exampleDir)) fs.mkdirSync(exampleDir, { recursive: true });
if (!fs.existsSync(nestedDir)) fs.mkdirSync(nestedDir, { recursive: true });

fs.writeFileSync(path.join(exampleDir, 'utilA.js'), `module.exports = { getA: () => 'Value from utilA' };`);
fs.writeFileSync(path.join(exampleDir, 'utilB.js'), `module.exports = { getB: (name) => \`Hello, \${name} from utilB\` };`);
fs.writeFileSync(path.nestedDir, 'utilC.js'), `module.exports = { getC: () => 'Value from nested utilC' };`);

// 2. Use export-files to load the modules
const modules = exportFiles(exampleDir, undefined, { recursive: true });

console.log('Exported module keys:', Object.keys(modules));
// Expected output: Exported module keys: [ 'utilA', 'utilB', 'utilC' ]

console.log('Call utilA.getA():', modules.utilA.getA());
// Expected output: Call utilA.getA(): Value from utilA

console.log('Call utilB.getB("World"):', modules.utilB.getB('World'));
// Expected output: Call utilB.getB("World"): Hello, World from utilB

console.log('Call utilC.getC():', modules.utilC.getC());
// Expected output: Call utilC.getC(): Value from nested utilC

// 3. Clean up the dummy directory
process.on('exit', () => {
  if (fs.existsSync(exampleDir)) {
    fs.rmSync(exampleDir, { recursive: true, force: true });
    console.log('Cleaned up temp_example_modules directory.');
  }
});

view raw JSON →