Skip to content

Instantly share code, notes, and snippets.

@danedavid
Created June 7, 2018 11:13
Show Gist options
  • Save danedavid/c1ae57e6eb6a7447e174bd92f4231321 to your computer and use it in GitHub Desktop.
Save danedavid/c1ae57e6eb6a7447e174bd92f4231321 to your computer and use it in GitHub Desktop.
Terminal command 'ls' using Node
const fs = require('fs');
fs.readdir('.', 'utf8', (err, files) => {
if ( err ) {
console.log('Error: ', err);
return;
}
let largestLength = files.slice().sort((a,b) => b.length - a.length)[0].length;
let columns = Math.floor( process.stdout.columns / largestLength );
let formattedString = '';
let j = 1;
files.sort((a,b) => b[0] - a[0]);
for ( let k = 0; k < files.length; k++ ) {
formattedString += `${files[k]}`.padEnd(process.stdout.columns / columns);
if ( ++j === columns ) {
console.log(formattedString.trim());
j = 0;
formattedString = '';
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment