Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get directory of a file name in Javascript

Tags:

javascript

How to get the directory of a file?

For example, I pass in a string

C:\Program Files\nant\bin\nant.exe 

I want a function that returns me

C:\Program Files\nant\bin 

I would prefer a built in function that does the job, instead of having manually split the string and exclude the last one.

Edit: I am running on Windows

like image 593
Graviton Avatar asked May 04 '09 02:05

Graviton


People also ask

How do you get a list of the names of all files present in a directory in Javascript?

To get a list of the names of all files present in a directory in Node. js, we can call the readdir method. const testFolder = './folder/path'; const fs = require('fs'); fs. readdir(testFolder, (err, files) => { files.

How do I get CWD in Javascript?

In Node. js, there are two built-in ways to get the current directory. You can either use the __dirname variable or the process. cwd() method to get the current folder.

How do I read a directory in node JS?

The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.


2 Answers

I don't know if there is any built in functionality for this, but it's pretty straight forward to get the path.

path = path.substring(0,path.lastIndexOf("\\")+1); 
like image 155
Phaedrus Avatar answered Sep 28 '22 00:09

Phaedrus


If you use Node.js, path module is quite handy.

path.dirname("/home/workspace/filename.txt") // '/home/workspace/' 
like image 40
W.Perrin Avatar answered Sep 28 '22 00:09

W.Perrin