DEV Community

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

Posted on

2 1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more