【问题标题】:Node js Get folder path from a fileNode js 从文件中获取文件夹路径
【发布时间】:2013-06-16 00:59:33
【问题描述】:

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

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 或者我需要处理字符串?

【问题讨论】:

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


    【解决方案1】:

    使用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');
    

    【讨论】:

    • 双反斜杠,否则你最终会转义随机字符。
    • 如果您从原始问题中的相对路径开始,您会这样做-let onlyPath = path.dirname(fs.realpathSync('config.json'));
    • 我希望始终使用@Kip 方法来使用realpathSync,它涵盖了绝对路径和相对路径
    • 只是为此添加警告。如果您的路径末尾没有文件名(即您对多个事物使用相同的代码),它将只是剥离路径中的最后一个目录。如果您 100% 确定文件路径中有一个文件,这是一个愚蠢的功能。
    【解决方案2】:

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

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

    【讨论】:

    • 这似乎与 5 年前发布的公认答案相同
    【解决方案3】:

    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:\\"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-28
      • 2017-11-03
      • 2010-10-14
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      相关资源
      最近更新 更多