2

I used path.join (__dirname, ...)to get the absolute path from node js.

But I don't know why is path.join better than string operations? like: __dirname + path...

Recently I learned that the ES2015 script supports the "template literals" syntax.

So, which of these three cases is the best? Of course, it seems to use a lot of path.join. I don't care if others use it a lot, but I wonder why I use path.join.

Case1: path.join

path.join(__dirname, 'public')

Case2: string operation

__dirname + '/public'

Case3: template literals

`${__dirname}/public`
유제환
  • 33
  • 4
  • 1
    Possible duplicate of [Do you need to use path.join in Node.js?](https://stackoverflow.com/questions/9756567/do-you-need-to-use-path-join-in-node-js) – Maxim Shoustin Aug 13 '17 at 04:28

1 Answers1

8

path.join() offers a couple features that neither of your other methods offer.

  1. It knows what the path separator is for the current platform which is different on Windows vs. other platforms. So, it is easier to write cross platform code using path.join() without writing any extra code.

  2. It inserts one and only one path separator between the pieces so if you're using variables, you don't have to even know if your variable already includes a path separator on it or not as path.join() will check and "do the right thing".

  3. It can join multiple pieces by just passing more than two arguments.

So, if you don't care about any of these advantages, then feel free to use either string addition or template literals.

It's a whole separate discussion about when to use template literals and when to use string addition. It is mostly personal opinion on which you prefer - there is no "right" answer. In general, I find template literals to make more readable code, but there are still some times when it makes sense to use string addition such as when building a string with several different pieces of code or a loop.

jfriend00
  • 683,504
  • 96
  • 985
  • 979