在Javascript中获取文件名的目录

时间:2021-07-11 23:59:41

How to get the directory of a file?

如何获取文件的目录?

For example, I pass in a string

例如,我传入一个字符串

C:\Program Files\nant\bin\nant.exe

I want a function that returns me

我想要一个返回我的函数

C:\Program Files\nant\bin

I would prefer a built in function that does the job, instead of having manually split the string and exclude the last one.

我宁愿使用内建函数来完成这项工作,而不是手工分割字符串并排除最后一个。

Edit: I am running on Windows

编辑:我在Windows上运行

8 个解决方案

#1


15  

I don't know if there is any built in functionality for this, but it's pretty straight forward to get the path.

我不知道是否有任何内置的功能,但这是非常直接的路径。

path = path.substring(0,path.lastIndexOf("\\")+1);

#2


8  

Use:

使用:

var dirname = filename.match(/(.*)[\/\\]/)[1]||'';

*The answers that are based on lastIndexOf('/') or lastIndexOf('\') are error prone, because path can be "c:\aa/bb\cc/dd".
(Matthew Flaschen did took this into account, so my answer is a regex alternative)

*基于lastIndexOf('/')或lastIndexOf('\')的答案容易出错,因为路径可以是“c:\aa/bb\cc/dd”。(Matthew Flaschen确实考虑到了这一点,所以我的回答是regex替代方案)

#3


7  

There's no perfect solution, because this functionality isn't built-in, and there's no way to get the system file-separator. You can try:

没有完美的解决方案,因为这个功能不是内置的,也没有办法获得系统文件分隔符。你可以尝试:

path = path.substring(0, Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"))); 
alert(path);

#4


2  

function getFileDirectory(filePath) {
  if (filePath.indexOf("/") == -1) { // windows
    return filePath.substring(0, filePath.lastIndexOf('\\'));
  } 
  else { // unix
    return filePath.substring(0, filePath.lastIndexOf('/'));
  }
}
console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin');
console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin');

#5


2  

Sorry to bring this back up but was also looking for a solution without referencing the variable twice. I came up with the following:

不好意思把这个问题提出来了,但是我们也在寻找一个解决方案,没有两次引用这个变量。我想到了以下几点:

var filepath = 'C:\\Program Files\\nant\\bin\\nant.exe';
    // C:\Program Files\nant\bin\nant.exe
var dirpath = filepath.split('\\').reverse().splice(1).reverse().join('\\');
    // C:\Program Files\nant\bin

This is a bit of a walk through manipulating a string to array and back but it's clean enough I think.

这有点像操作字符串到数组再返回,但我认为它已经足够干净了。

#6


1  

And this?

这吗?

If isn't a program in addressFile, return addressFile

如果在addressFile中不是程序,返回addressFile

function(addressFile) {
    var pos = addressFile.lastIndexOf("/");
    pos = pos != -1 ? pos : addressFile.lastIndexOf("\\");

    if (pos > addressFile.lastIndexOf(".")) {
        return addressFile;
    }

    return addressFile.substring(
        0,
        pos+1
    );
}


console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin\\');
console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin/nant/');
console.assert(getFileDirectory('/usr/thisfolderhaveadot.inhere') === '/usr/');

#7


0  

filepath.split("/").slice(0,-1).join("/"); // get dir of filepath
  1. split string into array delimited by "/"
  2. 将字符串分割成以"/"分隔的数组
  3. drop the last element of the array (which would be the file name + extension)
  4. 删除数组的最后一个元素(它将是文件名+扩展名)
  5. join the array w/ "/" to generate the directory path
  6. 加入数组w/ "/"以生成目录路径

such that

这样

"/path/to/test.js".split("/").slice(0,-1).join("/") == "/path/to"

#8


-2  

The core Javascript language doesn't provide file/io functions. However if you're working in a Windows OS you can use the FileSystemObject (ActiveX/COM).

核心的Javascript语言不提供文件/io函数。但是,如果您在Windows操作系统中工作,您可以使用文件系统对象(ActiveX/COM)。

Note: Don't use this in the client script-side script of a web application though, it's best in other areas such as in Windows script host, or the server side of a web app where you have more control over the platform.

注意:不要在web应用程序的客户端脚本中使用这个脚本,它最好用于其他领域,比如Windows脚本主机,或者web应用程序的服务器端,在那里您可以对平台进行更多的控制。

This page provides a good tutorial on how to do this.

这个页面提供了一个很好的关于如何做到这一点的教程。

Here's a rough example to do what you want:

这里有一个简单的例子来做你想做的:

   var fso, targetFilePath,fileObj,folderObj;

   fso = new ActiveXObject("Scripting.FileSystemObject");

   fileObj = fso.GetFile(targetFilePath);

   folderObj=fileObj.ParentFolder;

   alert(folderObj.Path);

#1


15  

I don't know if there is any built in functionality for this, but it's pretty straight forward to get the path.

我不知道是否有任何内置的功能,但这是非常直接的路径。

path = path.substring(0,path.lastIndexOf("\\")+1);

#2


8  

Use:

使用:

var dirname = filename.match(/(.*)[\/\\]/)[1]||'';

*The answers that are based on lastIndexOf('/') or lastIndexOf('\') are error prone, because path can be "c:\aa/bb\cc/dd".
(Matthew Flaschen did took this into account, so my answer is a regex alternative)

*基于lastIndexOf('/')或lastIndexOf('\')的答案容易出错,因为路径可以是“c:\aa/bb\cc/dd”。(Matthew Flaschen确实考虑到了这一点,所以我的回答是regex替代方案)

#3


7  

There's no perfect solution, because this functionality isn't built-in, and there's no way to get the system file-separator. You can try:

没有完美的解决方案,因为这个功能不是内置的,也没有办法获得系统文件分隔符。你可以尝试:

path = path.substring(0, Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"))); 
alert(path);

#4


2  

function getFileDirectory(filePath) {
  if (filePath.indexOf("/") == -1) { // windows
    return filePath.substring(0, filePath.lastIndexOf('\\'));
  } 
  else { // unix
    return filePath.substring(0, filePath.lastIndexOf('/'));
  }
}
console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin');
console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin');

#5


2  

Sorry to bring this back up but was also looking for a solution without referencing the variable twice. I came up with the following:

不好意思把这个问题提出来了,但是我们也在寻找一个解决方案,没有两次引用这个变量。我想到了以下几点:

var filepath = 'C:\\Program Files\\nant\\bin\\nant.exe';
    // C:\Program Files\nant\bin\nant.exe
var dirpath = filepath.split('\\').reverse().splice(1).reverse().join('\\');
    // C:\Program Files\nant\bin

This is a bit of a walk through manipulating a string to array and back but it's clean enough I think.

这有点像操作字符串到数组再返回,但我认为它已经足够干净了。

#6


1  

And this?

这吗?

If isn't a program in addressFile, return addressFile

如果在addressFile中不是程序,返回addressFile

function(addressFile) {
    var pos = addressFile.lastIndexOf("/");
    pos = pos != -1 ? pos : addressFile.lastIndexOf("\\");

    if (pos > addressFile.lastIndexOf(".")) {
        return addressFile;
    }

    return addressFile.substring(
        0,
        pos+1
    );
}


console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin\\');
console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin/nant/');
console.assert(getFileDirectory('/usr/thisfolderhaveadot.inhere') === '/usr/');

#7


0  

filepath.split("/").slice(0,-1).join("/"); // get dir of filepath
  1. split string into array delimited by "/"
  2. 将字符串分割成以"/"分隔的数组
  3. drop the last element of the array (which would be the file name + extension)
  4. 删除数组的最后一个元素(它将是文件名+扩展名)
  5. join the array w/ "/" to generate the directory path
  6. 加入数组w/ "/"以生成目录路径

such that

这样

"/path/to/test.js".split("/").slice(0,-1).join("/") == "/path/to"

#8


-2  

The core Javascript language doesn't provide file/io functions. However if you're working in a Windows OS you can use the FileSystemObject (ActiveX/COM).

核心的Javascript语言不提供文件/io函数。但是,如果您在Windows操作系统中工作,您可以使用文件系统对象(ActiveX/COM)。

Note: Don't use this in the client script-side script of a web application though, it's best in other areas such as in Windows script host, or the server side of a web app where you have more control over the platform.

注意:不要在web应用程序的客户端脚本中使用这个脚本,它最好用于其他领域,比如Windows脚本主机,或者web应用程序的服务器端,在那里您可以对平台进行更多的控制。

This page provides a good tutorial on how to do this.

这个页面提供了一个很好的关于如何做到这一点的教程。

Here's a rough example to do what you want:

这里有一个简单的例子来做你想做的:

   var fso, targetFilePath,fileObj,folderObj;

   fso = new ActiveXObject("Scripting.FileSystemObject");

   fileObj = fso.GetFile(targetFilePath);

   folderObj=fileObj.ParentFolder;

   alert(folderObj.Path);