Node file path

How to interact with file paths and operate in Node

Every file in the system has a path.

On Linux and macOS, the path may be similar to:

/users/flavio/file.txt

Windows computers are different and have the following structure:

C:\users\flavio\file.txt

You need to be careful when using paths in your application, because this difference must be taken into account.

You can include this module in the file using

const path = require('path')

You can start using its method.

Make information out of its way

Given a path, you can extract information from it using the following methods:

  • dirname: Get the parent folder of the file
  • basename: Get the file name part
  • extname: Get the file extension

example:

const notes = '/users/flavio/notes.txt'

path.dirname(notes) // /users/flavio path.basename(notes) // notes.txt path.extname(notes) // .txt

You can obtain the file name without extension by specifying the second parameter.basename:

path.basename(notes, path.extname(notes)) //notes

Use path

You can use the following methods to connect two or more parts of the pathpath.join():

const name = 'flavio'
path.join('/', 'users', name, 'notes.txt') //'/users/flavio/notes.txt'

You can use the following method to get the absolute path calculation of the relative pathpath.resolve():

path.resolve('flavio.txt') //'/Users/flavio/flavio.txt' if run from my home folder

In this case, the node will append/flavio.txtGo to the current working directory. If you specify the second parameter folder,resolveThe first will be used as the basis for the second:

path.resolve('tmp', 'flavio.txt')//'/Users/flavio/tmp/flavio.txt' if run from my home folder

If the first parameter starts with a slash, it means it is an absolute path:

path.resolve('/etc', 'flavio.txt')//'/etc/flavio.txt'

path.normalize()Is another useful function when it contains things like.or..Or double slash:

path.normalize('/users/flavio/..//test.txt') ///users/test.txt

Neither parsing nor normalization will check whether the path exists. They just calculate the path based on the information obtained.

Download mine for freeNode.js manual


More node tutorials: