API for opening files in a default applications


#1

I want to create a simple package to open files or directories whose paths are selected on Atom with their default applications( not with Atom itself) . What I mean is for pdf files I want my package to open with default pdf viewer. And when directory paths selected, I want my package to open with default filer. Are there any API available for this purpose? Any help will be appliciated.


#2

You don’t even need a package. I have this code in my init.coffee and it does the job.

# Open file in system default program.
{spawn} = require 'child_process'

atom.contextMenu.add {
  ".tree-view": [{
    label: "Open file in default program"
    command: "custom:open-in-default"
  }]
}

atom.commands.add ".tree-view", "custom:open-in-default", (evt) ->
  spawn evt.target.attributes.getNamedItem("data-path").value, {shell: true}

#3

Thank you for quick reply.
As you can see, I’m a novice to this issue.
I couldn’t find command “custom:open-in-default” from command palette. Did I miss something here? Should I install some other package in advance?

And I also couldn’t find getNameItem API(?) on Atom flight manual.

And another thing is I want to use this command for selected fullpath on “TextEditor area”, not on “Treeview pane”.
I’m sorry to bother you but please tell me some more.


#4

That command is defined below in the same snippet. It does not appear in the command palette, rather it will appear in the context menu (the right-click menu).

That is a DOM method, and not something unique to Atom. If you are not sure what properties it has (I certainly don’t know), try logging it to console and explore it that way.

You would need to set up a function which receives the selected path, and runs a shell command such as open ${path}. The exact syntax varies by platform, but macOS uses open. For how to do this, I recommend looking at the nodejs child_process module.


#5

Those two lines of code at the end are an entire command. You will find that many things can be done with very few lines of code, since the API is so well-developed.

And another thing is I want to use this command for selected fullpath on “TextEditor area”, not on “Treeview pane”.

All you need to do is get the last selection from the active editor. Same command, except that you’re making an API call to find the text to send instead of looking at a DOM node. Note that you can use this for other shell commands if you really want to (and don’t need the power provided by a package like process-palette).

{spawn} = require 'child_process'

atom.contextMenu.add {
  "atom-text-editor": [{
    label: "Run selection in shell or default program"
    command: "custom:open-in-default"
  }]
}

atom.commands.add ".tree-view", "custom:open-in-default", (evt) ->
  editor = atom.workspace.getActiveTextEditor()
  text = editor.getSelectedText()
  spawn text, {shell: true}