I wrote a little media library organizer app using Electron and Node, mainly as practice to learn the frameworks. The app reads in a directory, stores the contents to a local sqlite, and then displays the data in nicely formatted data tables. However, I was wondering if it was possible to add the functionality to then open these files in VLC. Searching really only turns up information for playing media files IN the Electron app itself but I want to be able to click a button in a row to open the corresponding file in VLC or equivalent media player. Is there any way to do this?
You can actually launch VLC as a "child process" of your Electron application.
Given you have stored the path to the media file in a variable called filepath
, you can use NodeJS's child_process
module like this:
var child_process = require ("child_process");
// Spawn VLC
var proc = child_process.spawn ("vlc", [ filepath ], { shell: true });
// Handle VLC error output (from the process' stderr stream)
proc.stderr.on ("data", (data) => {
console.error ("VLC: " + data.toString ());
});
// Optionally, also handle VLC general output (from the process' stdout stream)
proc.stdout.on ("data", (data) => {
console.log ("VLC: " + data.toString ());
});
// Finally, detect when VLC has exited
proc.on ("exit", (code, signal) => {
// Every code > 0 indicates an error.
console.log ("VLC exited with code " + code);
});
All of this data logging, via proc.stderr
, proc.stdout
and proc.on ("exit")
is optional, but if you want to only allow one single VLC instance to be spawned by your application at a time, you could set a global variable when spawning the first instance, remove it (or set it to false or similar) and wrap this whole block in an if () {}
so this code only allows one single instance to be running at a time.
Note that the child processes spawned this way are actually independent of your application; if your application exits before VLC has been closed, VLC will continue to run.