Get Off My Lawn
Get Off My Lawn

Reputation: 36299

Get directory from a file path or url

I am trying to get the directory location of a file, and I'm not sure how to get it. I can't seem to find a module that allows me to do this.

So for example say I have this string:

/this/is/a/path/to/a/file.html

how can I get this:

/this/is/a/path/to/a

I know I can use something like this:

path.substr(0, path.lastIndexOf("/") - 1);

But I am not sure if that is as good of a method as something that might be built in to node.

I have also tried:

var info = url.parse(full_path);
console.log(info);

and the result doesn't return what I am looking for, that gets the full path including the filename.

So, is there something built into node that can do this and do it well?

Upvotes: 25

Views: 63564

Answers (7)

wise king
wise king

Reputation: 49

You can get dirname with just with __dirname.

Upvotes: -1

cronoklee
cronoklee

Reputation: 6702

Using plain JS, this will work:

var e = '/this/is/a/path/to/a/file.html'
e.split("/").slice(0,-1).join("/")  //split to array & remove last element

//result: '/this/is/a/path/to/a'

OR... if you prefer a one liner (using regex):

"/this/is/a/path/to/a/file.html".replace(/(.*?)[^/]*\..*$/,'$1')

//result: '/this/is/a/path/to/a/'

OR... finally, the good old fashioned (and faster):

var e = '/this/is/a/path/to/a/file.html'
e.substr(0, e.lastIndexOf("/"))

//result: '/this/is/a/path/to/a'

Upvotes: 26

Ulad Kasach
Ulad Kasach

Reputation: 12808

filepath.split("/").slice(0,-1).join("/"); // get dir of filepath
  1. split string into array delimited by "/"
  2. drop the last element of the array (which would be the file name + extension)
  3. join the array w/ "/" to generate the directory path

Upvotes: 2

Hypaethral
Hypaethral

Reputation: 1477

Using path module of node.js:

path.dirname('/this/is/a/path/to/a/file');

returns

'/this/is/a/path/to/a'

Upvotes: 35

Stefan Steiger
Stefan Steiger

Reputation: 82146

For plain JavaScript, this will work:

function getDirName(e)
{
     if(e === null) return '/';

     if(e.indexOf("/") !== -1)
     {
         e = e.split('/')            //break the string into an array
         e.pop()                     //remove its last element
         e= e.join('/')              //join the array back into a string
         if(e === '')
              return '/';
         return e;
     }

     return "/";
}


var e = '/this/is/a/path/to/a/file.html'
var e = 'file.html'
var e = '/file.html'
getDirName(e)

Upvotes: -1

Jon Carter
Jon Carter

Reputation: 3406

I think you're looking for path.dirname

Upvotes: 3

sebnukem
sebnukem

Reputation: 8303

Have you tried the dirname function of the path module: https://nodejs.org/api/path.html#path_path_dirname_p

path.dirname('/this/is/a/path/to/a/file.html')
// returns
'/this/is/a/path/to/a'

Upvotes: 1

Related Questions