Skip to content

Instantly share code, notes, and snippets.

@masukomi
Forked from aackerman/application.js
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masukomi/177dfe05843216fb8c24 to your computer and use it in GitHub Desktop.
Save masukomi/177dfe05843216fb8c24 to your computer and use it in GitHub Desktop.
Preventing multiple electron application instances
var net = require('net');
var fs = require('fs');
var os = require('os');
var path = require('path');
// Create server to listen for additional application launches
function listenForNewProcesses(socketPath) {
// create a server for listening on the socket path
var server = net.createServer(function(connection) {
connection.on('data', function(data) {
console.log('Another instance of the application was launched and will terminate');
});
});
// listen on the socket path
server.listen(socketPath);
// log errors
server.on('error', function(error) {
console.error('Application server failed', error);
});
}
function deleteSocketFile(socketPath) {
// no need to delete the socket file on windows, pipes are cleaned up
if ( process.platform === 'win32' ) { return; }
if ( fs.existsSync(socketPath) ) {
try {
fs.unlinkSync(socketPath);
} catch (error) {
// Ignore ENOENT errors in case the file was deleted between the exists
// check and the call to unlink sync.
if (error.code != 'ENOENT') {
// rethrow the error
throw error;
}
}
}
}
// setup a default socket value
var DefaultSocketPath = process.platform === 'win32'
? '\\\\.\\pipe\\application-sock'
: path.join(os.tmpdir(), "application-#{process.env.USER}.sock");
function Application(options) {
// listen for new processes to connect so they can know
// to terminate themselves because an instance is already running
listenForNewProcesses(options.socketPath);
}
Application.init = function init(options) {
options = options || {};
options.socketPath = options.socketPath || DefaultSocketPath;
var app = require('app');
// application callback
var createApplication = function createApplication() {
return new Application(options);
};
// if the socket doesn't exist or the platform is windows
// attempt to connect to determine if another instance is running
if ( process.platform === 'win32' || fs.existsSync(socketPath) ) {
// attempt to connect on the socket path and if we can
// terminate the application, an instance is already running
var client = net.connect({ path: socketPath }, function(){
// write to the socket and terminate
client.write('{}', function() {
client.end();
app.terminate();
});
});
// continue with application startup if the client errors
// we couldn't write or connect so it probably doesn't exist
client.on('error', createApplication);
} else {
createApplication();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment