Reputation: 126
I am getting in trouble then using fs.rename in node.js app. I already use the function below and it works as I would expect it to work.
var fs =require("fs");
var path =require("path")
module.exports= function(oldPath, newPath){
oldPath=path.join(__dirname, "..", "documents", "bka" , oldPath);
newPath=path.join(__dirname, "..", "documents", "bka" , newPath);
fs.rename(oldPath, newPath, (err)=>{if (err) console.log(err)});
}
Then I tried to use the function for another case. oldPath exists. newPath doesn't exists. If I don't change newPath no error occurs. If I change it the error below occurs and I have no idea why:
{ Error: ENOENT: no such file or directory, rename '/home/ubuntu/workspace/documents/bka/7_Wall Street_1/9_Whg_Nr_22/7_bob' -> '/home/ubuntu/workspace/documents/bka/7_Wall Street_1/9_Whg_Nr_221/7_bob' at Error (native) errno: -2, code: 'ENOENT', syscall: 'rename', path: '/home/ubuntu/workspace/documents/bka/7_Wall Street_1/9_Whg_Nr_22/7_bob', dest: '/home/ubuntu/workspace/documents/bka/7_Wall Street_1/9_Whg_Nr_221/7_bob' }
would be great if you could help me. I have seen some other people had similar problems in the past but I didn't find any answer that could make me understand the problem.
Thanks amit
Upvotes: 4
Views: 8371
Reputation: 126
thanks for the response.
I kind of fixed it. The code is a mess now but it at least it does what it should.
var path =require("path");
var mkdirp =require("mkdirp");
var shell = require("shelljs");
var Promise= require("bluebird");
module.exports= function(oldPath, newPath){
oldPath=path.join(__dirname, "..", "documents", "bka" , oldPath);
newPath=path.join(__dirname, "..", "documents", "bka" , newPath);
var oldArr= oldPath.split("/");
var newArr= newPath.split("/");
var np="";
var op="";
var createDir=(path)=>{
return new Promise((resolve)=>{
mkdirp(path, (err)=>{
if (err) throw err
resolve(path)
});
});
}
var copy =(from, to)=>{
return new Promise((resolve)=>{
shell.cp("-R",from+"/*", to);
resolve();
});
}
var rm= (path)=>{
return new Promise((resolve)=>{
shell.rm("-R", path);
resolve();
});
}
var results=[]
for( var i=0; i<oldArr.length; i++){
op += oldArr[i]+"/";
np += newArr[i]+"/";
if(oldArr[i]!= newArr[i]){
Promise.resolve()
var result={}
result.from=op;
result.to=np;
results.push(result);
}
}
createDir(results[results.length-1].to)
.then(()=>{ copy(results[results.length-1].from, results[results.length-1].to)
.then(()=>{rm(results[0].from).then(()=>{
results.pop();
});
});
});
}
Upvotes: 0
Reputation: 203494
You're renaming the file .../9_Whg_Nr_22/7_bob
to .../9_Whg_Nr_221/7_bob
This will only work if the directory 9_Whg_Nr_221
already exists, and my guess is that it doesn't, and fs.rename
will not create that directory for you.
In these sorts of situations, where the target directory may not yet exist, you have to manually create the directory first, for instance using mkdirp
.
Upvotes: 4