简体   繁体   中英

path.join(__dirname, "foo", "bar") vs path.join(__dirname, "foo/bar")

And by the way, foo and bar would be string literals

I've seen a bunch of repositories that use both, "foo/bar" and "foo", "bar"

I did a benchmark with benchmark js with the following code (I also made a gist )

suite.add('foo/bar', function() {
    path.join(__dirname, 'foo/bar')
})
.add('foo, bar', function() {
    path.join(__dirname, 'foo', 'bar')
})
.on('complete', function() {
    console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run({ 'async': true });

And foo/bar was faster. But I still see a lot of code like path.join(__dirname, '..', '..', 'node_modules')

So is there any reason to use path.join(__dirname, 'foo', 'bar') ?

I'm also talking about path.resolve

There are three main benefits to using path.join() .

  1. It automatically checks for trailing separators so you will never get two separators together in the resulting path.

  2. It automatically uses the platform-specific path separator (which is a backslash on Windows).

  3. After joining the segments with the above logic, it then normalizes the path, resolving any . or .. segments.

So, you use path.join() for sure when you want any of this functionality. If you don't need any of these features, then you can go either way (with your own manual path construction or use path.join() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM