DEV Community

Cover image for 3 code pieces to work with file path in Node.js
Onelinerhub
Onelinerhub

Posted on

3 code pieces to work with file path in Node.js

1. How to extract filename from path

const path = require('path');
let file = path.basename('/home/joe/image.png');
Enter fullscreen mode Exit fullscreen mode
  • require('path') - module to work with file/dir path,
  • .basename( - return filename part of a given path,
  • /home/joe/image.png - sample path to extract filename from.

Original version, improve this code.

2. How to get file extension

const path = require('path');
let ext = path.extname('image.png');
Enter fullscreen mode Exit fullscreen mode
  • require('path') - module to work with file/dir path,
  • .extname( - returns extension of a given path string,
  • image.png - sample file path to get extension from.

Original version, improve this code.

3. How to get path dirname

const path = require('path');
let dir = path.dirname('/home/joe/image.png');
Enter fullscreen mode Exit fullscreen mode
  • require('path') - module to work with file/dir path,
  • .dirname( - return dir part of a given path,
  • /home/joe/image.png - sample path to return dir for.

Original version, improve this code.

Top comments (0)