Created
August 20, 2014 23:26
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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