Search code examples
javascriptwindowsmacosbackslashslash

Handle slash on Mac and Windows in JavaScript


In a JavaScript file I have:

__dirname.split('/')

This code was written on MAC and it works on that environment. However, this script crashes on my Windows because it can't find the directory, so in order to work I have to change it to this:

__dirname.split('\\')    

The problem is that I can't commit it like this because it will crash on his end after this since he is using MAC.

Is there any way I can edit this block of code in order to work on both envs ?

Thanks


Solution

  • You can use path.sep:

    const path = require('path');
    ...
    __dirname.split(path.sep)