Introduction
While there a bazillions of ways to generate a text file with all the directories and the respective files (Bash comes to mind), I wanted to explore Shell.js for doing this task so it could be chained together in a bigger set of Node.js tools I've been cobbling together recently. I also wanted to make it simpler than recent scripts I've written by foregoing Commander.js and just have it accept one argument which would be the directory to generate the report from.In theory, I should be able to execute this command and get a text file back with all the files found there and all the nested files and directories:
node app.js <directory>
Required skills and npm packages
You should be fairly comfortable with JavaScript and have some exposure to shell.js (0.8.3).
Required modules and variable setup
We'll need to require two modules (shell and fs), grab the user supplied directory (path
), and set up a variable to hold the list of items found therein (output
).
const shell = require('shelljs');
const fs = require('fs');
const path = process.argv[2];
var output = '';
...Generate the report
If the path is supplied, then we should inform the user that the script in generating the report, recursively gather all the contents of the target directories, and save out the data to a text file called directorySiteMap.txt.
...
if (path) {
console.log('Generating directorySiteMap.txt');
shell.ls('-LR', path).map(function(file) {
output += file + '\n';
});
fs.writeFileSync(directorySiteMap.txt, output);
...
Quit if path isn't supplied
If the path isn't supplied, the script should state as such to the user and gracefully quit.
...
} else {
console.log('Directory argument is required. Quitting.');
process.exit(1);
}
Wrapping up
Now we should save this script as
directorySiteMap.js
and execute it using this command: node directorySiteMap.js <directory>