synckit
![GitHub Release](https://img.shields.io/github/release/rx-ts/synckit)
![David Dev](https://img.shields.io/david/dev/rx-ts/synckit.svg)
![Code Style: Prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)
Perform async work synchronously in Node.js using worker_threads
, or child_process
as fallback, with first-class TypeScript support.
TOC
Usage
Install
yarn add synckit
npm i synckit
API
worker_threads
is used by default for performance, if you have any problem with it, you can set env SYNCKIT_WORKER_THREADS=0
to disable it and fallback to previously child_process
solution, and please raise an issue here so that we can improve it.
import { createSyncFn } from 'synckit'
const syncFn = createSyncFn(require.resolve('./worker'))
const result = syncFn(...args)
import { runAsWorker } from 'synckit'
runAsWorker(async (...args) => {
return result
})
You must make sure:
- if
worker_threads
is enabled (by default), the result
is serialized by Structured Clone Algorithm
- if
child_process
is used, the result
is serialized by JSON.stringify
Env variables
SYNCKIT_WORKER_THREADS
: whether or not enable worker_threads
, it's enabled by default, set as 0
to disableSYNCKIT_BUFFER_SIZE
: bufferSize
to create SharedArrayBuffer
for worker_threads
(default as 1024
), or maxBuffer
for child_process
(no default)SYNCKIT_TIMEOUT
: timeout
for performing the async job (no default)
TypeScript
If you want to use ts-node
for worker file (a .ts
file), it is supported out of box!
If you want to use a custom tsconfig as project instead of default tsconfig.json
, use TS_NODE_PROJECT
env. Please view ts-node for more details.
If you want to integrate with tsconfig-paths, please view ts-node for more details.
Benchmark
It is about 20x faster than sync-threads
but 3x slower than native for reading the file content itself 1000 times during runtime, and 18x faster than sync-threads
but 4x slower than native for total time.
And it's almost same as deasync
but requires no native bindings or node-gyp
.
See benchmark for more details.
You can try it with running yarn benchmark
by yourself. Here is the benchmark source code.
Changelog
Detailed changes for each release are documented in CHANGELOG.md.
License
MIT © JounQin@1stG.me