EN
Node.js - get directory path from file path
9
points
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