最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Which case is better for setting the path? "path.join() vs string operation vs template literals"

programmeradmin0浏览0评论

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`

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`
Share Improve this question asked Aug 13, 2017 at 3:40 유제환유제환 334 bronze badges 1
  • 1 Possible duplicate of Do you need to use path.join in Node.js? – Maxim Shoustin Commented Aug 13, 2017 at 4:28
Add a ment  | 

1 Answer 1

Reset to default 10

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论