Skip to content

Instantly share code, notes, and snippets.

@guillermosnipe
Last active September 17, 2018 15:35
Show Gist options
  • Save guillermosnipe/9532fcf779614d1fc00aa018fa075810 to your computer and use it in GitHub Desktop.
Save guillermosnipe/9532fcf779614d1fc00aa018fa075810 to your computer and use it in GitHub Desktop.
Adding carbon cli the ability to process files from a directory
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const fs = require( 'fs' );
const path = require( 'path' );
const codeSampleDir = './code-samples';
//Async forEach loop
async function asyncForEach(array, callback) {
let arrayLength = array.length;
for (let index = 0; index < arrayLength; index++) {
await callback(array[index], index, array)
}
}
// isDirectory helper function
function isDirectory (pathname) {
return fs.statSync(pathname).isDirectory();
}
function buildImages (dir) {
if (!isDirectory(dir)) {
console.error(`The entry dir MUST be a directory. You've provided a file instead.`);
process.exit(1);
}
try {
// Reading source directory looking for images to convert
fs.readdir( dir, function( err, files ) {
// If an error happens exit the process.
if (err) {
console.error("Could not list the directory.\r\n", err);
process.exit(1);
}
carbonStart(files, dir);
});
} catch (err) {
console.error("The directory can't be read. Try later.");
}
}
buildImages(codeSampleDir);
// Get Carbon image method
async function getCarbonImage(fileName, dir) {
let file = path.join(dir, fileName);
const { stdout, stderr } = await exec(`carbon-now ${file} -l 'images'`);
console.log('stdout:', stdout);
console.log('stderr:', stderr);
}
//carbon routine
const carbonStart = async(files, dir) => {
await asyncForEach(files, async function(file) {
await getCarbonImage(file, dir);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment