Ondrej Tokar Ondrej Tokar - 4 months ago 30
Node.js Question

How can I rename a file on the SFTP with NodeJs

Is there a way to rename a file on the SFTP?

This is what I use for downloading, I am using

scp2
node module:

client.scp({
'host': this.host,
'username': this.username,
'password': this.password,
'path': path
},'./', function(err) {
if (err){
return callback("File: "+path+" "+err);
}else{
return callback(null);
}
});


Maybe I could download the file, upload it with another name and remove the old one from the SFTP. But that is not neat.

I've looked through other modules such as this: https://www.npmjs.com/package/sftpjs that has some rename function implemented but I can't make it work. Any suggestion? It's quite obvious use case and I couldn't find anything.

EDIT:
Vijay's answer is correct. I was just doing it wrong.

My code:

// Download swush file from SFTP
var Client = require('sftpjs');
var c = Client();

c.on('ready', function () {
c.list(function (err, list) {
if (err) throw err;

console.dir(list);

c.end();
});
}).connect({
'host': this.host,
'username': this.username,
'password': this.password,
}).rename(path.concat(oldName), path.concat(newName), function(err){
if (err){
console.log("Error when renaming file: "+err)
}else{
console.log("Renaming file successful.");
}
});


Working code:

// Download swush file from SFTP
var Client = require('sftpjs');
var c = Client();

c.on('ready', function () {
c.rename(path.concat(oldName), path.concat(newName), function(err) {//only one parameter err is available for rename method.
if (err){
console.log("Error when renaming file: "+err)
}else{
console.log("Renaming file successful.");
}
});
}).connect({
'host': this.host,
'username': this.username,
'password': this.password,
});

Answer

You can use following lines of code for renaming file: You can use https://github.com/mscdex/node-ftp for getting success in renaming file.

var Client = require('ftp');

var c = new Client();
c.on('ready', function() {
    c.rename('foo.txt', 'foo-new.txt', function(err) {//only one parameter err is available for rename method.
      if (err) throw err;
      console.log("rename completed");
    });
});
c.connect({
 host : host,
 user : user,
 password : password
});

You can also use node-sftpjs module to achieve this as same way.