I just created my first ES6 module in Node, and first time using promises and I was hoping to get some feedback on it. I am the only developer at my current company, so I cannot get feedback here. I just want to make sure whoever comes behind me in the future can have a clean code base to work in.
'use strict';
var fs = require('fs');
var nodeSchedule = require('node-schedule');
class CronJob {
constructor(filePath, time, rule) {
this.filePath = filePath;
this.maxPdfAge = time || 86400000;
this.currentDate = Date.parse(new Date());
this.scheduleRule = rule || this.getDefaultRule();
}
schedule(callback) {
nodeSchedule.scheduleJob(this.scheduleRule, err => {
if (err) return callback(err);
this.scanFolder((err, info) => {
if (err) return callback(err, null);
return callback(null, info);
});
});
}
scanFolder(callback) {
scanDirectory(this.filePath)
.then(files => {
this.findOldPdfs(this.filePath, files, (err, info) => {
if (err) return callback(err, null);
return callback(null, info);
});
}).catch(err => {
callback(err, null);
});
}
findOldPdfs(filePath, pdfs, callback) {
var pdfDates = getPdfCreateDates(filePath, pdfs);
Promise.all(pdfDates)
.then(pdfs => {
this.deletePdfs(pdfs, (err, info) => {
if (err) return callback(err, null);
return callback(null, info);
});
})
.catch(err => {
callback(err, null);
});
}
deletePdfs(pdfObjects, callback) {
var pdfsToDelete = getPdfsToDelete(pdfObjects, this.currentDate, this.maxPdfAge);
Promise.all(pdfsToDelete)
.then(successMsgs => {
callback(null, successMsgs);
}).catch(err => {
callback(err, null);
});
}
getDefaultRule() {
var rule = new nodeSchedule.RecurrenceRule();
rule.dayOfWeek = [0, new nodeSchedule.Range(0, 6)];
rule.hour = 23;
rule.minute = 59;
rule.second = 0;
return rule;
}
}
/********************************************/
// Promise function wrappers
/********************************************/
function scanDirectory(filePath) {
return new Promise((resolve, reject) => {
fs.readdir(filePath, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
function getPdfCreateDates(filePath, files) {
var arrayOfPromises = [];
files.forEach(file => {
var pdfFile = filePath + '/' + file;
var statLookupPromise = new Promise((resolve, reject) => {
fs.stat(pdfFile, (err, info) => {
if (err) {
reject(err);
} else {
resolve({ filePath: pdfFile, dateTime: info.mtime });
}
});
});
arrayOfPromises.push(statLookupPromise);
});
return arrayOfPromises;
}
function getPdfsToDelete(pdfs, currentDate, maxPdfAge) {
var arrayOfPdfPromises = [];
pdfs.forEach(pdf => {
if (currentDate - maxPdfAge > pdf.dateTime) {
var deletePdfPromise = new Promise((resolve, reject) => {
fs.unlink(pdf.filePath, (err) => {
if (err) {
reject(err);
} else {
resolve(pdf.filePath + ' was deleted');
}
});
});
arrayOfPdfPromises.push(deletePdfPromise);
}
});
return arrayOfPdfPromises;
}
module.exports = CronJob;