Search code examples
linuxnode.jswindowsunc

UNC path construction on Linux


I've got a function that uses path.join to construct a UNC path for use by another (Windows) system (the Node.js application does not need access to it, it just needs to construct the path correctly):

function constructUncPath (fileName, userLastName) {
  var storageLocation = getStorageLocation(); // Returns a UNC base path
  var todayDateFormatted = moment().format('YYYYMMDD');
  return path.join(storageLocation, userLastName + '_' + todayDateFormatted + '_' + fileName);
}

On Windows it creates the path correctly, but on Linux it fails because it inserts forward slashes instead of backslashes:

 + expected - actual

      -\\path\to/user_20150101_file.txt
      +\\path\to\user_20150101_file.txt

Is there a way to force path.join to use backslashes instead of forward slashes?

Or should I just explicitly replace them after the join?


Solution

  • path.join() won't do it as it is picking up the forward slash character from the machine it is running on. There's lots of ways to write a path.join() replacement, but using .Replace("/", "\") is easiest.

    Incidentally, if you don't have to support Windows 9x, don't even bother. Windows will take a forward slash there just fine.