40a500c743 | ||
---|---|---|
.. | ||
lib | ||
node_modules/tslib | ||
LICENSE | ||
README.md | ||
package.json |
README.md
synckit
Perform async work synchronously in Node.js using worker_threads
with first-class TypeScript support.
TOC
Usage
Install
# yarn
yarn add synckit
# npm
npm i synckit
API
// runner.js
import { createSyncFn } from 'synckit'
// the worker path must be absolute
const syncFn = createSyncFn(require.resolve('./worker'), {
tsRunner: 'tsx', // optional, can be `'ts-node' | 'esbuild-register' | 'esbuild-runner' | 'tsx'`
})
// do whatever you want, you will get the result synchronously!
const result = syncFn(...args)
// worker.js
import { runAsWorker } from 'synckit'
runAsWorker(async (...args) => {
// do expensive work
return result
})
You must make sure, the result
is serializable by Structured Clone Algorithm
Options
bufferSize
same as envSYNCKIT_BUFFER_SIZE
timeout
same as envSYNCKIT_TIMEOUT
execArgv
same as envSYNCKIT_EXEC_ARGV
tsRunner
same as envSYNCKIT_TS_RUNNER
Envs
SYNCKIT_BUFFER_SIZE
:bufferSize
to createSharedArrayBuffer
forworker_threads
(default as1024
)SYNCKIT_TIMEOUT
:timeout
for performing the async job (no default)SYNCKIT_EXEC_ARGV
: List of node CLI options passed to the worker, split with comma,
. (default as[]
), see alsonode
docsSYNCKIT_TS_RUNNER
: Which TypeScript runner to be used, it could be very useful for development, could be'ts-node' | 'esbuild-register' | 'esbuild-runner' | 'swc' | 'tsx'
,'ts-node'
is used by default, make sure you have installed them already
TypeScript
ts-node
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.
esbuild-register
Please view esbuild-register
for its document
esbuild-runner
Please view esbuild-runner
for its document
swc
Please view @swc-node/register
for its document
tsx
Please view tsx
for its document
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.cjs and benchmark.esm for more details.
You can try it with running yarn benchmark
by yourself. Here is the benchmark source code.
Sponsors
1stG | RxTS | UnTS |
---|---|---|
Backers
1stG | RxTS | UnTS |
---|---|---|
Changelog
Detailed changes for each release are documented in CHANGELOG.md.