节点js从文件中获取文件夹路径

时间:2013-06-19 13:12:48

标签: node.js command-line-interface npm

有没有办法获取包含特定文件的文件夹的路径。

fs.realpathSync('config.json', []);

返回类似

的内容
G:\node-demos\7-node-module\demo\config.json

我只需要

G:\node-demos\7-node-module\demo\ 
or
G:\node-demos\7-node-module\demo\

是否有任何api或我需要处理字符串?

3 个答案:

答案 0 :(得分:107)

使用path.dirname

// onlyPath should be G:\node-demos\7-handlebars-watch\demo
var onlyPath = require('path').dirname('G:\node-demos\7-node-module\demo\config.json');

答案 1 :(得分:1)

只需安装path模块并使用它,

var path = require('path');
path.dirname('G:\node-demos\7-node-module\demo\config.json')

// Returns: G:\node-demos\7-node-module\demo

答案 2 :(得分:0)

require("path").dirname(……) 中断,如果您的路径未明确指定其目录。

require("path").dirname("./..")
// "."

您可以考虑改为使用require("path").join(……, "../")。它还保留了尾随的分隔符。

require("path").join("whatever/absolute/or/relative", "../")
// "whatever/absolute/or/" (POSIX)
// "whatever\\absolute\\or\\" (Windows)
require("path").join(".", "../")
// "../" (POSIX)
// "..\\" (Windows)
require("path").join("..", "../")
// "../../" (POSIX)
// "..\\..\\" (Windows)
require("path").win32.join("C:\\", "../")
// "C:\\"