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("https://stackoverflow.com/") - 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?

Using path module of node.js:

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

returns

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

Using plain JS, this will work:

var e="/this/is/a/path/to/a/file.html"
e.split("https://stackoverflow.com/").slice(0,-1).join("https://stackoverflow.com/")  //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("https://stackoverflow.com/"))

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

I think you’re looking for path.dirname

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

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'

For plain JavaScript, this will work:

function getDirName(e)
{
     if(e === null) return "https://stackoverflow.com/";

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

     return "https://stackoverflow.com/";
}


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


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