Return a object from inside the parent function.
const setupProcess = (websocket) => {
let state = 'idle'
const startProcess = () => {
state = 'running'
websocket.onmessage = (event) => {
const data = JSON.parse(event.data)
// do something with data
}
}
const stopProcess = () => {
state = 'idle'
websocket.onmessage = null
}
return {
startProcess,
stopPorcess
}
}
module.exports = setupProcess
Then you can access it like that:
const setupProcess = require('./setupProcess')
const router = require('./router')
const ws = require('ws')
const app = express()
const port = 3000
connectDatabase(mongoDbUrl)
const ws = new WebSocket('wss//test-websocket.com/ws')
const methods = setupProcess(ws) // initialized
app.use(router(methods))
app.listen(port, () => {
console.log(`Server is up on port ${port}`)
})
router.js
const express = require('express')
const router = new express.Router()
module.exports = (methods) => {
router.post('/process/start', async (req, res) => {
// should be able to startProcess() from here
//methods.startProcess();
})
router.post('/process/start', async (req, res) => {
// should be able to stopProcess from here
//methods.stopProcess();
})
// return the router
// so express can use it
return router;
}
CLICK HERE to find out more related problems solutions.