Created
November 30, 2013 18:00
-
-
Save ryanflorence/7722329 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// npm install cli-prompt | |
var prompt = require('cli-prompt'); | |
var fs = require('fs'); | |
var files = [ | |
{path: './foo', src: 'foo'}, | |
{path: './bar', src: 'bar'} | |
]; | |
saveFiles(files, function() { | |
console.log('done'); | |
}); | |
function saveFiles(files, callback) { | |
files.forEach(attemptSave); | |
function attemptSave(file, index, arr) { | |
fs.exists(file.path, function(exists) { | |
if (exists) { | |
prompt(file.path+' exists, overwrite? [y|n]', function(overwrite) { | |
if (overwrite == 'y') save(); | |
maybeCallback(); | |
}); | |
} else { | |
save(); | |
maybeCallback(); | |
} | |
}); | |
function save() { | |
console.log('-> saved file', file.path); | |
fs.writeFile(file.src, maybeCallback); | |
} | |
function maybeCallback() { | |
if (index == arr.length - 1) callback(); | |
} | |
} | |
} | |
function saveFilesSync(files) { | |
files.forEach(function(file) { | |
if (fs.existsSync(file.path)) { | |
if (prompt(file.path+' exists, overwrite? [y|n]') !== 'y') { | |
return; | |
}; | |
} | |
fs.writeFileSync(file.path, file.src); | |
}); | |
} |
Yeah, you want to do those in order. Try async.each
, it should help.
Alternately, write a function that calls itself with the next element, or a callback if there are no more elements. I usually use .pop and check xs.length for this kind of thing.
the sync version was added just for my sanity...
@jesusabdullah, I brought in async
but then it only prompted once, I am begging for you to write the code for me up there.
@jesusabdullah to the rescue https://gist.github.com/jesusabdullah/7722499
I'm curious to know what confuses about this problem. I think it's important to understand why it's difficult.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Save this file and run it, you'll see the first time its great, but the second time when the files exists you get:
./foo exists, overwrite? [y|n]./bar exists, overwrite? [y|n]n
Is the
async
lib supposed to help me here somehow?