简体   繁体   中英

How to get specific file path name using node js

Is this even possible to get specific file path from url

my file path is like

testing\abc\pqr\subfolder1\anotherFolder

or

testing\sufolder\anothersubfolder\abc\pqr\xyz\mno

my output will look like this

testing\abc\pqr

or
testing\sufolder\anothersubfolder\abc

Its should remove last few name of a folder and provide only specific length folder name from the start of the path which I will pass in an array

You can split the path and just grab the number of segments you want from the front. Since you're showing Windows-style paths, here's some sample code that uses the Windows path separator. This can be adapted to use path.sep if you want a cross platform version. Since your example paths do not start with a leading slash, this code assumes that.

 function getFrontPathSegments(fullPath, numSegments) { let pieces = fullPath.split("\\"); return pieces.slice(0, numSegments).join("\\"); } // example usage let front = getFrontPathSegments("testing\\sufolder\\anothersubfolder\\abc\\pqr\\xyz\\mno", 3); console.log(front);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM