How to determine the OS path separator in JavaScript?

Viewed 73439

How can I tell in JavaScript what path separator is used in the OS where the script is running?

5 Answers

Afair you can always use / as a path separator, even on Windows.

Quote from http://bytes.com/forum/thread23123.html:

So, the situation can be summed up rather simply:

  • All DOS services since DOS 2.0 and all Windows APIs accept either forward slash or backslash. Always have.

  • None of the standard command shells (CMD or COMMAND) will accept forward slashes. Even the "cd ./tmp" example given in a previous post fails.

As already answered here, you can find the OS specific path separator with path.sep to manually construct your path. But you can also let path.join do the job, which is my preferred solution when dealing with path constructions:

Example:

const path = require('path');

const directory = 'logs';
const file = 'data.json';

const path1 = `${directory}${path.sep}${file}`;
const path2 = path.join(directory, file);

console.log(path1); // Shows "logs\data.json" on Windows
console.log(path2); // Also shows "logs\data.json" on Windows

Just use "/", it works on all OS's as far as I know.

Related