Skip to content

Instantly share code, notes, and snippets.

@Arlodotexe
Last active July 8, 2018 06:02
Show Gist options
  • Save Arlodotexe/c7f8d390298fac03ba39a0f2a454131e to your computer and use it in GitHub Desktop.
Save Arlodotexe/c7f8d390298fac03ba39a0f2a454131e to your computer and use it in GitHub Desktop.
Check a folder for changed files in NodeJS
// Run at least once. Directory is the directory to check, Datapath should point to a json file with an empty array (`[]`) where Node can store file data
function checkForChangedFiles(directory, datapath) {
return new Promise(resolve => {
let filedata = require(datapath);
let changedfiles = [];
fs.readdir(directory, async (err, files) => {
if (err) throw new Error('Unabled to check for existing files. Reason: readdir failed. \n' + err);
for (let i in files) {
if ((function() {
for (let o = filedata.length - 1; o > -1; o--) {
if (filedata[o].name === files[i]) return true;
}
})() && files[i] !== 'node_modules') {
console.log('Found existing file data: ' + files[i]);
for (let o in filedata) {
if (filedata[o].name == files[i]) {
if (filedata[o].size !== fs.statSync(directory + '\\' + files[i]).size) {
console.log(files[i] + ' has changed');
changedfiles.push(files[i]);
filedata.splice(o);
filedata.push({
"name": files[i],
"size": fs.statSync(directory + '\\' + files[i]).size
});
fs.writeFileSync(datapath, JSON.stringify(filedata), undefined, err => {
if (err) throw new Error('Unable to save file data. Reason: writeFileSync failed. \n' + err);
filedata = require(datapath);
});
}
}
}
} else if (files[i] !== 'node_modules') {
changedfiles.push(files[i]);
console.log('File not registered. Saving data...');
filedata.push({
"name": files[i],
"size": fs.statSync(directory + '\\' + files[i]).size
});
fs.writeFileSync(datapath, JSON.stringify(filedata), undefined, err => {
if (err) throw new Error('Unable to save file data. Reason: writeFileSync failed. \n' + err);
filedata = require(datapath);
});
}
}
resolve(changedfiles);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment