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:


how can I get this:


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);

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?

Using path module of node.js:




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):


//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'

I think you’re looking for path.dirname

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

Have you tried the dirname function of the path module:

// returns

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"

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts