Home > Software engineering >  Node.js: Check the root of the path.format()
Node.js: Check the root of the path.format()

Time:10-28

See the following example for the path.format():

require('path').format({ root: '/Users/joe', name: 'test', ext: 'txt' }) //  '/Users/joe/test.txt'

This example is written in nodejs.dev and it is said that the output is as follows:

/Users/joe/test.txt

But I have tested this code on both Linux and Windows, but the result is as follows:

/Users/joetesttxt

What is the reason for this difference?
Is the example of this site wrong?

CodePudding user response:

The example shown is for POSIX, where as Windows & Linux have different ways of doing it (because of the differences in file structure).

If we use the opposite function parse, and convert C:\\Users\\joe\\test.txt to the object we'd need to use in format, we get.

path.parse('C:\\Users\\joe\\test.txt')
// returns
{
  root: 'C:\\',
  dir: 'C:\\Users\\joe',
  base: 'test.txt',
  ext: '.txt',
  name: 'test'
}

So this gives an example as to what you'd need to give format for Windows.

If we do the same in Linux, we get.

path.parse('/home/joe/test.txt')
{
  root: '/',
  dir: '/home/joe',
  base: 'test.txt',
  ext: '.txt',
  name: 'test'
}

We can however, omit root and base as they are represented in dir and name ext respectively.

  • Related