Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created November 30, 2013 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryanflorence/7722329 to your computer and use it in GitHub Desktop.
Save ryanflorence/7722329 to your computer and use it in GitHub Desktop.
// 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);
});
}
@ryanflorence
Copy link
Author

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?

@jfhbrook
Copy link

Yeah, you want to do those in order. Try async.each, it should help.

@jfhbrook
Copy link

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.

@ryanflorence
Copy link
Author

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.

@ryanflorence
Copy link
Author

@jesusabdullah to the rescue https://gist.github.com/jesusabdullah/7722499

@polotek
Copy link

polotek commented Nov 30, 2013

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