问题
I am using node.js and express to create an application, I have a file TCPServer.js that i use to continually poll a TCP/IP server. I want to be able to send a single HTTP request to a database that reads in the IP Address and port number, then uses that data to call my TCPServer.js file which in turn polls the TCP server.
Reading the database works, the HTTP request works for a single call to the TCPServer, but whenever I try and continually poll the TCP server i get a 1 poll response from the server then a 500 error thrown.
So if with just getInputData(ipAddress, connPort)
in TCPServer.js then the HTTP request works no problem and returns the response from my TCP Server once and a 200 response. With setInterval(getInputData(ipAddress, connPort), 2000)
I get the data once and a 500 error response. Can I get this to poll every 2 seconds?
TCPServer.js
function getInputData(ipAddress, port) {
"Function for polling TCP Server runs in here"
}
const iModStart = function startInputModule(ipAddress, connPort) {
setInterval(getInputData(ipAddress, connPort), 2000)
}
module.exports = iModStart
route handler for running the http request
const iModuleConnect = require('../utils/TCPServer')
//run the polling to input module
router.get('/connections_connect/:id', async (req, res) => {
const _id = req.params.id
try {
const connection = await Connection.findById(_id)
if (!connection) {
return res.status(404).send()
}
if(connection) {
console.log(connection.ipAddress)
console.log(connection.port)
iModuleConnect(connection.ipAddress, connection.port)
}
res.send(connection)
} catch(e) {
res.status(500).send()
}
})
module.exports = router
回答1:
The problem is that setInterval
requires a callback function as its first argument, but you pass it the result of your already executed getInputData
function.
Obviously this works once as the function is exectued before the first interval, but as soon as the interval is reached after 2000 ms, there is no callback to call, and node will throw an TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
error.
To fix this you need to bind the function arguments to getInputData
and pass this as a callback to setInterval
:
const iModStart = function startInputModule(ipAddress, connPort) {
setInterval(getInputData.bind(getInputData, ipAddress, connPort), 2000);
}
来源:https://stackoverflow.com/questions/62248954/run-a-node-js-file-continuously-using-an-http-request