How to rename a local file or folder using Firefox Addon SDK Javascript?

How to rename a local file or folder using Firefox Addon SDK Javascript?

Wow that’s weird, I just checked out the SDK File IO docs and they don’t have a move function! That is really weird!

I verified by:

// Import SDK Stuff
var COMMONJS_URI = 'resource://gre/modules/commonjs';
var {require} = Cu.import(COMMONJS_URI + '/toolkit/require.js', {});
var notifications = require("sdk/notifications");
var fileIO = require("sdk/io/file");

console.log(fileIO)

and there was no move function!

So do this:

var {Cu} = require('chrome');
var {TextDecoder, TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});

var platfromPathToMyFileToRename = OS.Path.join(OS.Constants.Path.desktopDir, 'oldname');

var platformPathToMyFileWithNewName = OS.Path.join(OS.Constants.Path.desktopDir, 'newname')

var promise_rename = OS.File.move(platfromPathToMyFileToRename, platformPathToMyFileWithNewName, {noOverwrite:true}); // it does not matter if you set noOverwrite to true or false, the file is not overrwritten, simply renamed

promise_rename.then(
    function(aVal) {
        console.log('succesfully renamed!')
    },
    function(aReason) {
        console.error('failed to rename!, error is:', aReason);
    }
).catch(
    function(aCatch) {
        console.error('you coded something wrong!, error:', aCatch);
    }
);

Renaming something is just a move of a file to the same directory with a new name. That’s how the operation is done on the file system.

This code above will rename a folder on your desktop named oldname to newname

Here are the docs on OS.File

OS.File is the recommended way to do file io.

1 Like

Thank you very much noitidart! This definitely solved my problem. You are awesome!