Skip to content

Instantly share code, notes, and snippets.

@stelcheck

stelcheck/test-listen.sh

Last active Jun 14, 2017
Embed
What would you like to do?
Socket files in Node.js
#!/usr/bin/env bash
function printResult() {
echo ""
echo "=============================="
[[ ${1} == 0 ]] && echo "success" || echo "failed"
echo "=============================="
}
# With this path, the file will be truncated to 'file.s'
dirPath=/tmp/a/b/c/aaaaaaaa/b/c/c/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/allyourbasearebelongtous/
# With this path, the file will not be listed at all - even higher up in the directory tree!
# Even worse, even if you delete the whole directory tree and re-create it, the socket file will
# still be detected as being used by Node; this means that if you run this script more than once
# with this path, the first run will result in a pass/fail case, but all subsequent runs will
# end up in a fail/fail case!
# dirPath=/tmp/a/b/c/aaaaaaaa/b/c/c/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/d/allyourbasearebelongtous/evenlongerpath/
read -r -d '' jsSource << EOF
const net = require('net')
const fs = require('fs')
const path = require('path')
const SOCK_FILE = path.join(__dirname, 'file.sock')
console.log('Sock file located at:', SOCK_FILE)
try {
fs.unlinkSync(SOCK_FILE)
} catch (error) {
console.log('failed to remove sock file', error.message, error.code)
}
net.createServer(() => true).listen(SOCK_FILE, () => setTimeout(() => process.exit(), 1000))
EOF
echo ""
echo "-- Creating Directory"
mkdir -p "${dirPath}"
pushd "${dirPath}"
echo "${jsSource}" > index.js
echo ""
echo "------------------------------------------------------------"
echo "-- Starting server for the first time - should exit properly"
echo "------------------------------------------------------------"
echo ""
node index.js
ls -lah
printResult ${?}
echo ""
echo "-----------------------------------------------------"
echo "-- Starting server for the second time - should crash"
echo "-----------------------------------------------------"
echo ""
node index.js
printResult ${?}
echo ""
echo "-- Cleaning up"
popd
rm -rf "${dirPath}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment