Languages
[Edit]
EN

Node.js - get directory path from file path

9 points
Created by:
Selina-Miranda
337

In this short article, we would like to show how in Node.js, get a directory path when we have a file path.

Quick solution (example index.js file):

const path = require('path');

const filePath = '/path/to/file.txt';
const dirPath = path.dirname(filePath);

console.log(dirPath);  // /path/to

Running:

node ./index.js

Output:

/path/to

 

TypeScript / ESM version

It is required to configure TypeScript compilation and add definitions for 'path'.

import * as path from 'path';

const filePath = '/path/to/file.txt';
const dirPath = path.dirname(filePath);

console.log(dirPath);  // /path/to

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join