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

nonunicorn

Onelinerhub

Posted on August 4, 2022

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.

💖 💪 🙅 🚩
nonunicorn
Onelinerhub

Posted on August 4, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related