bobbyrne01
bobbyrne01

Reputation: 6735

Create a platform independent path string

I'm using the Mozilla addon sdk for development and need to create a file on the local system.
Currently I use the statement below but feel it may not cover all platforms.
Running the statement on Windows 7 and Windows XP returns:

console.log(system.platform);
winnt

Running it on Linux returns:

console.log(system.platform);
linux

Is there a more reliable way to create the fullPath string, without having to check contents of system.platform?

pathToFile = Cc["@mozilla.org/file/directory_service;1"]
    .getService(Ci.nsIProperties).get("Home", Ci.nsIFile).path;

if (system.platform.indexOf("win") == 0) {
    fileSeparator = "\";

}else{
    fileSeparator = "/";
}

fullPath=pathToFile + fileSeparator + 'myFile.txt'

Upvotes: 0

Views: 223

Answers (3)

jsantell
jsantell

Reputation: 1268

The SDK has a 'fs/path' module that has parity with Node's path API

Upvotes: 0

nmaier
nmaier

Reputation: 33162

I'd like to point out an alternative to @Kashif's answer.

Use FileUtils.getFile(), which is just a convenience function, essentially doing multiple .append()s, one per item in the parts array.

Cu.import("resource://gre/modules/FileUtils.jsm");
var file = FileUtils.getFile("Home", ["myFile.txt"]);
var path = file.path;

Upvotes: 0

Kashif
Kashif

Reputation: 1263

Just a little modfication to your code should do the trick

var file = Cc["@mozilla.org/file/directory_service;1"]
                .getService(Ci.nsIProperties).get("Home", Ci.nsIFile);

file.append("myFile.txt");

var fullPath = file.path;

Upvotes: 1

Related Questions