node.js Node js从文件中获取文件夹路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17192150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node js Get folder path from a file
提问by blessenm
Is there a way to get the path to a folder that holds a particular file.
有没有办法获取包含特定文件的文件夹的路径。
fs.realpathSync('config.json', []);
returns something like
返回类似的东西
G:\node-demos-node-module\demo\config.json
I just need
我只需要
G:\node-demos-node-module\demo\
or
G:\node-demos-node-module\demo\
Is there any api for this or will I need to process the string?
是否有任何 api 或者我需要处理字符串?
回答by hereandnow78
use path.dirname
// onlyPath should be G:\node-demos-handlebars-watch\demo
var onlyPath = require('path').dirname('G:\node-demos\7-node-module\demo\config.json');
回答by Subhashi
Simply install pathmodule and use it,
只需安装path模块并使用它,
var path = require('path');
path.dirname('G:\node-demos-node-module\demo\config.json')
// Returns: G:\node-demos-node-module\demo
回答by Константин Ван
require("path").dirname(……)breakswhen your path does not explicitly specify its directory.
require("path").dirname(……)当您的路径未明确指定其目录时会中断。
require("path").dirname("./..")
// "."
You may consider using require("path").join(……, "../")instead. It preserves the trailing separator as well.
你可以考虑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:\"

