Created
December 27, 2021 16:27
-
-
Save krutoo/3faae3b11ad176f6e1ba2ca6d6dbf50e to your computer and use it in GitHub Desktop.
simple jsesc() in worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Worker, isMainThread, parentPort } from 'worker_threads'; | |
import jsesc from 'jsesc'; | |
const generateId = (count => () => count++)(0); | |
let escape; | |
if (isMainThread) { | |
const worker = new Worker(new URL('./escape.mjs', import.meta.url)); | |
// таблица "идентификатор вызова -> promise resolver" | |
const buffer = {}; | |
// когда worker нам отвечает - резолвим promise ответом и удаляем resolver из буфера | |
worker.on('message', ({ id, payload }) => { | |
buffer[id](payload); | |
delete buffer[id]; | |
}); | |
escape = data => new Promise(resolve => { | |
const id = generateId(); | |
buffer[id] = resolve; | |
// используем JSON.stringify() ДО отправки сообщения worker'у чтобы не копировать объект | |
worker.postMessage({ id, data: JSON.stringify(data) }); | |
}); | |
} else { | |
parentPort.on('message', ({ id, data }) => { | |
const payload = jsesc(data, { | |
json: true, | |
isScriptContext: true, | |
}); | |
parentPort.postMessage({ id, payload }); | |
}); | |
} | |
export { escape }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pino from 'pino'; | |
import { createServer } from 'http'; | |
import { escape } from './escape.mjs'; | |
async function main () { | |
const logger = pino(); | |
let counter = 0; | |
const server = createServer(async function (req, res) { | |
const payload = await escape({ counter }); | |
logger.info({ counter }); | |
counter++; | |
res.writeHead(200, { responseType: 'application/json' }); | |
res.end(payload); | |
}); | |
const port = 8080; | |
server.listen(port, () => console.log(`Server started on port ${port}`)); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment