Languages
[Edit]
EN

TypeScript / Node.js - split path to directories array with file names

0 points
Created by:
maciek211
425

In this article, we would like to show you how to split path to directories array with file name in Node.js.

1. Install node types with the following command:

npm install --save @types/node

2. Import path module using:

import * as path from 'path';

3. Use string split() method with path.sep argument.

Note:

The path.sep provides the platform-specific path segment separator:

  • \ on Windows
  • / on POSIX

Practical example

import * as path from 'path';

const indexPath: string = 'C:\\projects\\app\\index.js'; // example path
const pathParts: string[] = indexPath.split(path.sep); // directories and file names array

console.log(pathParts);

Output:

[ 'C:', 'projects', 'app', 'index.js' ]

References

  1. Path | Node.js v16.9.0 Documentation

See also

  1. Node.js - split path to directories array with file names (JavaScript solution)

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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