0

I have this code that calls the nfc-forum-emulate-tag4 command on a file that the code also creates, containing a NDEF text record of the data received in the POST request. However, nfc-forum-emulate-tag4 runs indefinitely until the tag is scanned or until the process is killed. I want to, every time I get a POST request, kill the previous process and run another one. I have found that with the below code, the execSync blocks the POST request until the emulation process completes, but when I use exec instead of execSync, the command doesn't actually run. (Terrible) code:

const { execSync } = require('child_process')
const express = require('express')
const fs = require('fs')
const app = express()
function buildNFC(text) {
    const hex = Buffer.from(text)
    const length = text.length+3 
    const initial = Buffer.from([0xd1, 0x01, length, 0x54, 0x02, 0x65, 0x6e])
    return Buffer.concat([initial, hex])
}
var child;
app.post("/", function(req, res) {
    const nfcbuffer = buildNFC(req.query.code)
    fs.writeFileSync("/home/pi/nfc", nfcbuffer)
    res.send("Sent " + nfcbuffer.toString('hex'))
    try {
        if(child) {
                console.log(`pid: ${child.pid}`)
                execSync(`killall ${child.pid}`, {stdio: 'inherit'})
                child = null
        }
        else {
                console.log(`no child running`)
        }
        child = execSync(`cd /home/pi && nfc-emulate-forum-tag4 ./nfc`, {stdio: 'inherit'})
    } catch {}
})
app.listen(3000, () => console.log("Listening on port 3000..."))

Thanks in advance!

Dominik
  • 6,078
  • 8
  • 37
  • 61
  • Why don't you just use [`child.kill(...)`](https://nodejs.org/api/child_process.html#subprocesskillsignal). – jfriend00 Jan 30 '22 at 22:15
  • Also, `catch {}` is evil because it hides errors so you wouldn't even know they were happening. You should at least log an error you get there. – jfriend00 Jan 30 '22 at 22:15

0 Answers0