Skip to content

Instantly share code, notes, and snippets.

@ptdecker
Created August 20, 2014 23:26
Show Gist options
  • Save ptdecker/e7b117cd6de84556ddb6 to your computer and use it in GitHub Desktop.
Save ptdecker/e7b117cd6de84556ddb6 to your computer and use it in GitHub Desktop.
Automatically cleaning up a socket on Ubuntu 14.04 when 'Ctrl-C' is used to terminate node.js
/* This addresses a problem with the 'net-watcher.js' example in Jim Wilson's
* "Node.js The Right Way" book when running his 'net-watcher.js' example under
* Ubuntu 14.04 (and probably some other *nixs too).
*/
'use strict';
const
fs = require('fs'),
net = require('net'),
filename = process.argv[2],
server = net.createServer(function(connection) {
console.log('Subscriber connected.');
connection.write(JSON.stringify({type: 'watching',file: filename})+"\n");
let watcher = fs.watch(filename, function() {
connection.write(JSON.stringify({type: 'changed',file: filename,timestamp: new Date()}) + "\n");
});
connection.on('close', function() {
console.log('Subscriber disconnected.');
watcher.close();
});
});
if (!filename) {
throw Error('No target filename was specified.');
}
//Here is the additional 'secret sauce' to clean up the socket
process.on('SIGINT', function() {
console.log('\nClosing socket');
server.close(function() {
process.exit(1)
});
});
server.listen('/tmp/watcher.sock', function() {
console.log('Listening for subscribers...');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment