Search code examples
javascriptnode.jspathoperating-systemtemp

path separator across os platforms


from nodejs documentation on fs.mkdtemp

const tmpDir = '/tmp';
const subdir = '/com.domain.app';

!fs.existsSync(tmp + subdir) ? fs.mkdirSync(tmp + subdir) : null;

// This method is *CORRECT*:
const path = require('path');
fs.mkdtemp(tmpDir + path.sep + subdir + path.sep, function(err, folder){
  if (err) throw err;
  console.log(folder);
});

My question is related to path.sep and temp directories and I want the code to be platform agnostic, and to be able to run on multiple platforms.

  1. what will be the value of path.sep across all nodejs platforms.
  2. what is the value of tmp directory across all nodejs platforms.
  3. is /tmp available on windows?
  4. any suggestions for above code when it comes to temp directories/paths

Thanks


Solution

  • Use os.tmpDir and path.join functions for cross platform code.

    var tmp = require('os').tmpDir();
    var dest = path.join(tmp, "com.domain.app");
    
    !fs.existsSync(dest) ? fs.mkdirSync(dest) : null;
    

    Reference. Writing cross platform node