Skip to content

Instantly share code, notes, and snippets.

@weisk
Created October 7, 2017 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weisk/a658b47dcc2093b123a9339cea623001 to your computer and use it in GitHub Desktop.
Save weisk/a658b47dcc2093b123a9339cea623001 to your computer and use it in GitHub Desktop.
Util.promisify example - read files from directory, parse JSONs, copy
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const { ncp } = require('ncp');
const readDir = promisify(fs.readdir);
const readFile = promisify(fs.readFile);
const copyDir = promisify(ncp);
console.log('Parsing i18n files...')
readDir('i18n')
.then((filenames) => {
return filenames.filter((filename) => filename.endsWith('.json'))
})
.then((filenames) => {
let files = filenames.map((filename) => {
let filepath = path.join('i18n', filename);
console.log('\t' + filepath);
return readFile(filepath, 'utf-8')
});
return Promise.all(files);
})
.then((files) => {
let jsons = files.map((file) => Promise.resolve(JSON.parse(file)));
return Promise.all(jsons);
})
.then(() => {
return copyDir('i18n', 'build/i18n');
})
.then((result) => {
console.log('i18n files processed correctly');
})
.catch((err) => {
console.error(err);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment