Reputation: 85
function checkFileName(n = 0) {
return new Promise((resolve, reject) => {
fs.open("./npm"+n+".txt", 'r', function(err, res) {
if (err) {
resolve("./npm"+n+".txt")
} else {
n++
checkFileName(n)
}
})
})
}
checkFileName().then(Name => {
console.log(Name)
})
but it's not resolve anything where's the wrong ?
Upvotes: 0
Views: 147
Reputation: 1156
Please change checkFileName(n)
to checkFileName(n).then(resolve)
One of the solutions would be as follows:
function checkFileName(n = 0) {
return new Promise((resolve) => {
const filePath = "./npm"+n+".txt";
fs.open(filePath, 'r', function(err, res) {
if (err) {
resolve(filePath)
} else {
checkFileName(n+1).then(resolve)
}
})
})
}
checkFileName().then(Name => {
console.log(Name)
})
Upvotes: 0
Reputation: 4272
Any specific reason you is doing it like that ?
// Node.js program to demonstrate the
// fs.readdir() method
// Import the filesystem module
const fs = require('fs');
const path = require('path');
// Function to get current filenames
// in directory with specific extension
fs.readdir(__dirname, (err, files) => {
if (err)
console.log(err);
else {
console.log("\Filenames with the .txt extension:");
files.forEach(file => {
if (path.extname(file) == ".txt")
console.log(file);
})
}
})
Instead of reading a file at the time, you can read the hole dir and iterate over them returned files
Upvotes: 1