I have a JSON object having a key of file names and an attribute of its corresponding new name. I need to recursively search a directory to check if the file exist and then rename it using the new name attribute.
I tried following the guide here: node.js fs.readdir recursive directory search.
let newNames = {"file.txt":{"oldName":"file.txt","newName":"PREFIX_file.txt"}};
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach(function(file) {
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
if (!--pending) done(null, results);
});
} else {
results.push(file);
if (!--pending) done(null, results);
}
});
});
});
};
let folderPath = 'C:\\Users\\ericute';
walk(folderPath, function(err, results) {
if (err) throw err;
results.forEach(file => {
let filePath = path.dirname(file);
let newName = filesForRenaming[path.basename(file)].newName;
fs.rename(path.resolve(file), path.resolve(filePath, newName), (err) => {
if (err) console.log(err);
});
})
});
Executing the code above, I keep getting this error:
{[Error: ENOENT: no such file or directory, rename 'C:\Users\ericute\file.txt' -> 'C:\Users\ericute\PREFIX_file.txt']
errno: -4058,
code: 'ENOENT',
syscall: 'rename',
path: 'C:\\Users\\ericute\\file.txt',
dest: 'C:\\Users\\ericute\\PREFIX_file.txt'}
I'm absolutely sure that all files are there and since it goes through the fs.lstatSync, I am assuming that it can see the file. What am I doing wrong here?