I've written a node script which generates a set of files and populates them automatically. However I've noticed in the output that the success messages come quite a bit after the call message.
I am not very familiar with promises or callbacks apart from when I use them in pre-existing code. How would I go about writing the following to run in a step-by-step manner?
var fileGen = function(componentName) {
// Each createFile instance should run only after the previous one has completed.
createFile('view.php', componentName)
createFile('style.styl', componentName)
createFile('script.js', componentName)
createFile('style.print.styl', componentName)
// finishUp should only run when all createFile instances have completed.
finishUp()
}
var createFile = function (fileName, componentName, doc) {
// Tell the user what is happening
console.log(chalk.blue('\nCreating', fileName, '...'))
// Bring in the view.php scaffold file
var scaffold = './scaffold/' + fileName
fs.readFile(scaffold, 'utf8', function (err, data) {
if (err) return console.log(chalk.red(err))
var result = data.replace(/%cname%/g, componentName)
if (doc) {
var d = new Date()
result = result.replace(/%cfname%/g, doc.componentName)
result = result.replace(/%cdesc%/g, doc.componentDesc)
result = result.replace(/%cauthor%/g, doc.userName)
result = result.replace(/%cagithub%/g, doc.userGithub)
result = result.replace(/%creationdate%/g, d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear())
}
fs.writeFile('./src/components/' + componentName + '/' + fileName, result, function (err) {
if (err) return console.log(chalk.red(err))
console.log(chalk.green(fileName, 'created!'))
})
})
}
I feel like this is something I should be able to do (and probably have done before) but for some reason I can't get my brain around it today.