Skip to content

Instantly share code, notes, and snippets.

@stelcheck
Last active June 14, 2017 04:18
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 stelcheck/78c35a0a691de1e25a3a413519cc3fcb to your computer and use it in GitHub Desktop.
Save stelcheck/78c35a0a691de1e25a3a413519cc3fcb to your computer and use it in GitHub Desktop.
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