Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs get file name from absolute path?

Tags:

path

node.js

fs

How can I get the file name from an absolute path in Nodejs?

e.g. "foo.txt" from "/var/www/foo.txt"

I know it works with a string operation, like fullpath.replace(/.+\//, ''), but I want to know is there an explicit way, like file.getName() in Java?

like image 323
fxp Avatar asked Nov 06 '13 11:11

fxp


People also ask

How do I find the filename in node js?

Fs. basename(path) : returns the file name with extension. Fs. basename(path) : returns the file name without extension.

What is Basename in node js?

Definition and Usage. The path. basename() method returns the filename part of a file path.

What is __ Dirname in node?

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.


2 Answers

Use the basename method of the path module:

path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'

Here is the documentation the above example is taken from.

like image 144
Victor Stanciu Avatar answered Oct 17 '22 21:10

Victor Stanciu


To get the file name portion of the file name, the basename method is used:

var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var file = path.basename(fileName);

console.log(file); // 'python.exe'

If you want the file name without the extension, you can pass the extension variable (containing the extension name) to the basename method telling Node to return only the name without the extension:

var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var extension = path.extname(fileName);
var file = path.basename(fileName,extension);

console.log(file); // 'python'
like image 69
Rubin bhandari Avatar answered Oct 17 '22 23:10

Rubin bhandari