How to determine the OS path separator in JavaScript?

前端 未结 5 1813
你的背包
你的背包 2020-12-15 02:21

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

5条回答
  •  半阙折子戏
    2020-12-15 02:57

    As already answered here, you can find the OS specific path separator with path.join 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
    

提交回复
热议问题