1.2.13 • Published 4 days ago

@devtea2027/reprehenderit-quaerat-tempora-vero v1.2.13

Weekly downloads
-
License
MIT
Repository
github
Last release
4 days ago

@devtea2027/reprehenderit-quaerat-tempora-vero

npm version Build Status js-standard-style

A streaming way to send data to a Node.js Worker Thread.

install

npm i @devtea2027/reprehenderit-quaerat-tempora-vero

Usage

'use strict'

const ThreadStream = require('@devtea2027/reprehenderit-quaerat-tempora-vero')
const { join } = require('path')

const stream = new ThreadStream({
  filename: join(__dirname, 'worker.js'),
  workerData: { dest },
  workerOpts: {}, // Other options to be passed to Worker
  sync: false, // default
})

stream.write('hello')

// Asynchronous flushing
stream.flush(function () {
  stream.write(' ')
  stream.write('world')

  // Synchronous flushing
  stream.flushSync()
  stream.end()
})

In worker.js:

'use strict'

const fs = require('fs')
const { once } = require('events')

async function run (opts) {
  const stream = fs.createWriteStream(opts.dest)
  await once(stream, 'open')
  return stream
}

module.exports = run

Make sure that the stream emits 'close' when the stream completes. This can usually be achieved by passing the autoDestroy: true flag your stream classes.

The underlining worker is automatically closed if the stream is garbage collected.

External modules

You may use this module within compatible external modules, that exports the worker.js interface.

const ThreadStream = require('@devtea2027/reprehenderit-quaerat-tempora-vero')

const modulePath = require.resolve('pino-elasticsearch')

const stream = new ThreadStream({
  filename: modulePath,
  workerData: { node: 'http://localhost:9200' }
})

stream.write('log to elasticsearch!')
stream.flushSync()
stream.end()

This module works with yarn in PnP (plug'n play) mode too!

Emit events

You can emit events on the ThreadStream from your worker using worker.parentPort.postMessage(). The message (JSON object) must have the following data structure:

parentPort.postMessage({
  code: 'EVENT',
  name: 'eventName',
  args: ['list', 'of', 'args', 123, new Error('Boom')]
})

On your ThreadStream, you can add a listener function for this event name:

const stream = new ThreadStream({
  filename: join(__dirname, 'worker.js'),
  workerData: {},
})
stream.on('eventName', function (a, b, c, n, err) {
  console.log('received:', a, b, c, n, err) // received: list of args 123 Error: Boom
})

Post Messages

You can post messages to the worker by emitting a message event on the ThreadStream.

const stream = new ThreadStream({
  filename: join(__dirname, 'worker.js'),
  workerData: {},
})
stream.emit('message', message)

On your worker, you can listen for this message using worker.parentPort.on('message', cb).

const { parentPort } = require('worker_threads')
parentPort.on('message', function (message) {
  console.log('received:', message)
})

License

MIT

columnwalkmovesetPrototypeOflengthcensorextensionastlazymake dirfile systemdescriptoriteratevarsbrowserrgbreadablestreamFunction.prototype.namechromiumbddfsi18ngdprtsPromiselook-uptelephoneoperating-systemhandlersweaksetauthenticationfilterarktyperegularjoisigtermunicodedescriptorsfull-widthnested cssUint32ArrayloggingUnderscoreqsES8ponyfillgradients css3Array.prototype.findLastperformantsortedmomentasynccommand-lineprunefiglettaskmkdirconfigarraybuffershrinkwrapsignalsreduxStreamshttpsshimiterationprotobootstrap cssclassesfullwidthclidynamodbeslimitedupstringifytypescriptJSON-SchemaawaitelasticachewarningInt32ArrayemojidefaultArray.prototype.flatMapvalidatejsdifffpscreateidBigUint64ArraysequencesetImmediatecallboundmkdirsarraytypesclass-validatorECMAScript 2018dataViewslotpersistentwatcherinternal slotES7isConcatSpreadableclassnameECMAScript 2015ES2018eslint-plugininputnumbertostringtagownstreamcallbindStyleSheetprogressmacostrimRightsignalarraysdatelaunchlistenerstestprocessglobalappjapaneseidentifiersstructuredClonebrowserslistelmprivatetypedBigInt64ArraymatcheslintconfigES3endpointWeakSetAsyncIteratorcharacterconfigurablecorsconcatMaplruwrapobjmapreducecoreprettytouchdeep-copymixinsutilitiescallECMAScript 3wafeslintplugintoArraycloneWebSocketssetterreadgetintrinsicimportiamless.jsaccessorECMAScript 7xdgstyleguide$.extendvalidationenvironmentsttyreact-hook-formfind-uprm -frrmdeep-clonefetch_.extendelectrontypeofxhrparsingmoduletakeestreeeventDispatcherString.prototype.matchAlllogpromiseshooksArrayopenuuidargparsecomparegrouphottrimEndhasOwnPropertycjkpropertiesdropexpressTypeScriptinternalprefixconsumetrimartUint8ArraygetPrototypeOfcode pointssetutil.inspectMapmiddlewarepipefunctionalreplaylinuxfullratelimitcolorshigher-orderjwtinloadbalancingvariables in cssfolderlintinterruptssidepathzodECMAScript 2020formattypedarrayexit-codepackage manageres2017tapeless mixinsformsESnextrestfulRFC-6455scheme-validationspawnECMAScript 2022io-tsgetcharactersprotobufrdssuperagenttddmatchesopensUint8ClampedArraypostcss-pluginsigintdeepgetoptwindowsserializationtermcallbackkarmaenumerableexeArrayBufferstylesmergetoSortedlibphonenumberES2022cryptFloat32ArraysliceECMAScript 6css variablepositivees6es8dataviewregular expressionsglacierdependenciesmochareact-hooksjsonpathmimekeyssqspredictable.envHyBiformattinglimitschemaurlArray.prototype.flattenmodulesUint16Arrayincludeses2018negative zerocodesregeximportexporttypeerrorJSONdirectorywgetes5dataES2021computed-typesdefineSymboles-shim APIrequirereducertesterconsolehelpersec2queryparentflattenieenvironmentbundlingsesReactiveExtensionsquoteStreamimmertoolsparserstylingefficientenvflatpatchtoolkitnamesESstatusstylesheetequalitystringifiermruviewclassnamesboundwalkingwhichpostcssnativenameeslintbuffersFloat64ArrayWeakMapless compilerprototypesymlinkshastypanionregular expressionasciimatchAllconcatmapdiffoncetypesaferemoveduplexObject.keyscloudfrontdatastructurepolyfilltimeTypedArraycopypushkeyomitweakmapbufferthrottleObject.isoffsetstartdirMicrosoftfixed-widthrangeerrorhasOwnyupArray.prototype.findLastIndexqueueMicrotaskrm -rfstartercloudformationintrinsicurlsfseventsebscore-jssyntaxPushtrimStartES2015-0visualcollectiondependency managerminimalsymlinkreducevariableschildfluxschemeURLsortsomerandompackage.jsona11yformpreprocessorWebSocketwhatwgbundlerconcurrencyhttpexitendercurlfastclonefindES2016ES2023extralinewrapCSSpropertysnsassertiontextdeepclonebindinstallstoragegatewayoptimistRxJSdeterministicstdlibrecursiveavamime-dbECMAScript 2021deepcopyECMAScript 2016specsettingsamazonajvwatchings3validcss-in-jsredux-toolkiteast-asian-widthworker__proto__cloudsearch256indicatorcircularshamsearchmonorepoObject.getPrototypeOfbootstrap lesscloudwatchworkflownodeloggerextendkinesiserrorECMAScript 2019ES2020fast-clonepicomatchspinnersdayjsbluebirdgetternpmpackagesSettraversees2015nodejssafefindLastIndexhashjsyamlfastmimetypesnopespinnercloudtrailargsjestsuperstructinvarianttypedarraysbyteLengthArray.prototype.containsinspectsharedbeanstalklanguageobjectbcryptless cssagentswfspeedfindupkoreanlesscssiswatchFilepackagechannelcolourlastexecreact-testing-libraryargumentequalajaxArray.prototype.includesYAMLargumentsES2019String.prototype.trimCSSStyleDeclarationapielblockfileimmutablebyteOffsetsameValueZerocommandercss lesstyped arraythroatsyntaxerrorwidtheventslivecompile lesshardlinksObject.fromEntriesfastcopycall-bindcoercibleObservablesform-validationRegExp.prototype.flagsoptionURLSearchParamspyyamlserializesymbolsArrayBuffer.prototype.slicegetOwnPropertyDescriptorES6emitinferenceprivate dataRxcolumns@@toStringTagfunctiondefinePropertyReflect.getPrototypeOfwordbreakconnectexpressionbrowserlistfast-deep-copyratebatchpassworddotenvargvObjectidlerobustmkdirptypees-abstractcompilerwatchgroupByeditorreuseexecutableflagwritejasminejshintuninstallmakechaiguidquerystringlessmetadataroutervestparseReactiveXstyledebuggercmdassertssimpledbrfc4122iterator0Int8Arrayglobalsreactes2016xtermSymbol.toStringTageveryfast-deep-cloneawesomesauceTypeBoxcssreal-timecacheassignES5RegExp#flagsmobileentriesstableArrayBuffer#sliceproxyaccessibilityECMAScript 2023promisetestinginstallerArray.prototype.filterl10nparentsansiroute53awshookformshebangflagsphonegradients cssmulti-packagereadablees7openerescapeObject.assignencryptionstateloadingdebugdomworkspace:*preserve-symlinkswritableObject.definePropertysinatraxdg-openObject.entriesutilautoscalingbytewaitoptimizerdescriptionlinkterminalairbnbcommand[[Prototype]]genericsautoprefixerchinesecall-boundlookchromeperformanceArray.prototype.flatwordwrappropcollection.es6jsdomoutput
1.2.13

4 days ago

1.2.12

5 days ago

1.2.11

6 days ago

1.2.10

7 days ago

1.2.9

8 days ago

1.2.8

9 days ago

1.2.7

10 days ago

1.2.6

11 days ago

1.2.5

12 days ago

1.2.4

13 days ago

1.2.3

14 days ago