This code hasn't been tested exhaustively - I would love suggestions about a testing library.
Critical, Optional and Positive feedback are more then welcome.
const fs = require('fs');
/**
* strip all comments and create a new file with only code
* @param {int} file name to clean..
* @return {int} function returns 0 at the end.
*/
function clean(file) {
const inputFileName = file;
// create output file name. e.g: test.js -> test_CLEAN.js
let outputFileName = inputFileName.split('.');
outputFileName[0] += '_CLEAN';
outputFileName = outputFileName.join('.');
// clean output file old data
fs.writeFile(outputFileName, ``, (err) => {
if (err) {
console.log(err);
}
});
// comments regex defentions
// lines starts with // where // can have spaces before for indentation
const singleLineComment = /^\s*\/\//;
// start skipping lines on /* can have spaces before
const multiLineCommentStart = /^\s*\/\*/;
// stop skipping lines on */ end the end of the line
const multiLineCommentEnd = /\*\/$/;
// mixed lines with code and inline comments
const singleLineCommentAfterCode = /[;]\s*\/\//;
// skip lines bool
let skipLine = false;
// load input file to memory, split it by lines, filter white space lines, then loop over each line
fs.readFileSync(inputFileName, 'utf-8')
.split(/\n/)
.filter((line) => line != '')
.forEach((line) => {
// return in a forEach() callback is equivalent to continue in a conventional for loop.
if (multiLineCommentStart.test(line)) {
skipLine = true;
return;
}
if (multiLineCommentEnd.test(line)) {
skipLine = false;
return;
}
if (singleLineComment.test(line)) {
return;
}
if (singleLineCommentAfterCode.test(line)) {
line = line.split(' //')[0];
}
// append lines to output file
if (!skipLine) {
// append additional \n at the end of a blocks (after '};')
line = line === '};' ? line + '\n' : line;
fs.appendFileSync(outputFileName, `${line}\n`, (err) => {
if (err) {
// append failed
console.log(err);
}
});
}
});
return 0;
}