Run a node.js file continuously using an HTTP request

二次信任 提交于 2020-07-22 06:07:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!