使用HTTP请求连续运行node.js文件

问题描述 投票:1回答:1

我正在使用node.js并表示要创建一个应用程序,我有一个文件TCPServer.js,可用于不断轮询TCP / IP服务器。我希望能够将单个HTTP请求发送到读取IP地址和端口号的数据库,然后使用该数据调用我的TCPServer.js文件,该文件依次轮询TCP服务器。

[读取数据库有效,HTTP请求适用于对TCPServer的单个调用,但是每当我尝试不断轮询TCP服务器时,我都会从服务器收到1轮询响应,然后抛出500错误。

因此,如果TCPServer.js中仅包含getInputData(ipAddress, connPort),则HTTP请求不会有问题,并从我的TCP Server返回一次响应,并返回200响应。使用setInterval(getInputData(ipAddress, connPort), 2000),我将获得一次数据和500错误响应。我可以每2秒轮询一次吗?

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

用于运行http请求的路由处理程序


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

javascript node.js express httprequest
1个回答
0
投票
显然,在第一个时间间隔之前执行该功能一次,但是一旦在2000 ms之后达到该时间间隔,就不会调用任何回调,并且节点将抛出TypeError [ERR_INVALID_CALLBACK]: Callback must be a function错误。]

要解决此问题,您需要将函数参数绑定到getInputData,并将其作为回调传递给setInterval

const iModStart = function startInputModule(ipAddress, connPort) { setInterval(getInputData.bind(getInputData, ipAddress, connPort), 2000); }

© www.soinside.com 2019 - 2024. All rights reserved.