Reputation: 693
I am just getting used to Node programming, but I have come across this execution issue which I am slightly confused about.
I am trying to test if a write path already exists and if it does then ask the user for input.
function testPath(fileName) {
fs.exists(path.resolve('.', fileName), function(exists) {
//the filepath already exists, ask for user confirmation
if(exists) {
process.stdin.on('keypress', function (str, key) {
//print result of keypress to console
console.log("str: ", str, " key: ", key);
if ((str.toLowerCase() == "n") || (~["y", "n"].indexOf(str.toLowerCase()))) {
return false;
}
else {
return true;
}
});
}
else {
//the filepath does not already exist - return true
return true;
}
console.log("Filename in the target directory already exists, would you like to overwrite? (y/n)");
});
}
This function as a whole will be be resolved (or not) by a promise called on it.
The message to user and wait for keypress seem to action in the correct way but it sticks in a loop and never returns even on a valid keypress, does anyone know why this would be?
Upvotes: 1
Views: 41
Reputation: 1593
If you want to use it as a promise, you need to return a promise:
function testPath(fileName) {
return new Promise((resolve, reject) => {
fs.exists(path.resolve('.', fileName), function(exists) {
//the filepath already exists, ask for user confirmation
if(exists) {
process.stdin.on('keypress', function (str, key) {
//print result of keypress to console
console.log("str: ", str, " key: ", key);
if ((str.toLowerCase() == "n") || (~["y", "n"].indexOf(str.toLowerCase()))) {
return reject();
}
else {
return resolve();
}
});
}
else {
//the filepath does not already exist - return true
return resolve();
}
console.log("Filename in the target directory already exists, would you like to overwrite? (y/n)");
});
}
})
Upvotes: 2