Skip to content

Instantly share code, notes, and snippets.

@Tarabyte
Last active February 28, 2019 12:24
Show Gist options
  • Save Tarabyte/a609bc4f8b63077c496088cfd038ce1f to your computer and use it in GitHub Desktop.
Save Tarabyte/a609bc4f8b63077c496088cfd038ce1f to your computer and use it in GitHub Desktop.
Nested callbacks
addStepsAttachments(fileName, folder, callback) {
fileName = '12345';
fs.readdir(folder, 'utf8', function(err, filesList) {
if (!err && filesList.length > 0) {
const results = [];
const matchingFiles = filesList
.filter(file => file.startsWith(fileName))
.map(file => path.resolve(folder, file));
// just in case there were no matching files
done()
matchingFiles.forEach(file => {
fs.readFile(filePath, {encoding: 'base64'}, function(err, data) {
if (!err && data) {
results.push(data);
done()
} else {
callback(err);
}
});
});
// callback if all matching files were loaded
function done(){ if(result.length === matchingFiles.length) callback(null, results)}
} else {
callback(`Dir ${dirPath} is empty or some error happened: ${err}`, []);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment