【问题标题】:How to get the name of the active file in Atom?如何在 Atom 中获取活动文件的名称?
【发布时间】:2015-06-28 00:12:18
【问题描述】:

我想获取 Atom 1.0 包中当前文件的名称。我知道如何获取文件的完整路径,但我只想获取路径的文件名部分。这是我到目前为止的代码(取自atom-terminal):

editor = atom.workspace.getActivePaneItem()
file = editor?.buffer?.file
filepath = file?.path

我尝试阅读文档以查看是否已经存在这样的属性,但据我所知,窗格项没有记录。在https://atom.io/docs/api/v1.0.0 以外的其他地方是否有可用的文档?

如果没有属性,是否有适当的标准函数以独立于平台的方式从filepath 中提取路径的文件部分?

【问题讨论】:

    标签: coffeescript atom-editor


    【解决方案1】:

    @jacwah 提供的方法在 atom 1.18 中不再有效。根据API docs,您可以使用以下代码获取路径:

    atom.workspace.getActiveTextEditor()?.getPath()
    

    【讨论】:

    • getBaseName 仍然有效,但在编辑器上无效。 @jacwah 在 editor.buffer.file 对象上提到了这个函数。访问编辑器的方式已经改变,没有文件对象。 atom.workspace.getActiveTextEditor().buffer.file.getBaseName() 工作得很好。
    • ? 在代码中做了什么?如果我包含它,我会收到错误。
    【解决方案2】:

    使用file.getBaseName()。这将只返回file 路径的文件名部分。我通过将文件记录到控制台并检查它的属性发现了这一点。

    editor = atom.workspace.getActivePaneItem()
    file = editor?.buffer?.file
    filename = file?.getBaseName()
    

    您也可以使用 node.js path 模块的 basename 函数。

    path = require('path')
    
    editor = atom.workspace.getActivePaneItem()
    file = editor?.buffer?.file
    filename = path.basename(file?.path)
    

    【讨论】:

      【解决方案3】:

      使用 .getTitle():

      atom.workspace.getActiveTextEditor()?.getTitle()
      

      【讨论】:

      • 这可能行得通,但如果用户自定义它或实际保存一个名为“untitled”的文件怎么办? getPath 似乎更贴切。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      相关资源
      最近更新 更多