Reputation: 36299
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
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
Reputation: 12808
filepath.split("/").slice(0,-1).join("/"); // get dir of filepath
Upvotes: 2
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
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
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