Skip to content

Instantly share code, notes, and snippets.

@EmilienD
Last active March 16, 2018 09:48
Show Gist options
  • Select an option

  • Save EmilienD/4782841979af52da4ce4beced4bf0df6 to your computer and use it in GitHub Desktop.

Select an option

Save EmilienD/4782841979af52da4ce4beced4bf0df6 to your computer and use it in GitHub Desktop.
generate an index.js file as a commonjs style module
// usage: `node index-dot-js-maker.js <target directory>`
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const path = require('path');
const _ = require('lodash');
const cwd = process.cwd();
const maindir = path.resolve(cwd, process.argv[process.argv.length - 1]);
const indexFilenameMapper = filename => path.resolve(maindir, filename, 'index.js');
const fileExistsMapperAsync = filePath => fs.accessAsync(filePath, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
const isJs = filename => filename.match(/^.*\.js$/);
const isSpec = filename => filename.match(/^.*\.spec\.js$/);
const isIndex = filename => filename.match(/index\.js/);
fs.readdirAsync(maindir)
.then((filenames) => {
const jsFiles = filenames
.filter(filename => isJs(filename) && !isSpec(filename) && !isIndex(filename))
.map(filename => filename.replace('.js', ''));
const folderPromises = filenames
.filter(filename => !isJs(filename))
.map(filename => fileExistsMapperAsync(indexFilenameMapper(filename))
.then(exists => exists && filename)
);
return Promise.filter(jsFiles.concat(folderPromises), val => val); // remove falsy values from "exists" check
})
.then((filesToIndex) => {
const orderedFiles = filesToIndex.sort();
const requireLines = orderedFiles
.map(filename => `const ${_.camelCase(filename)} = require('./${filename}');`)
.join('\n');
const exportsLines = orderedFiles
.map(filename => ` ${_.camelCase(filename)},`)
.join('\n');
const indexDotJsFile =
`${requireLines}
module.exports = {
${exportsLines}
};
`;
fs.createWriteStream(path.resolve(maindir, 'index.js')).end(indexDotJsFile);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment