New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

scramjet-core

Package Overview
Dependencies
Maintainers
1
Versions
152
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

scramjet-core

A pluggable minimal version of Scramjet that focuses only on stream transform and exposes only core features

  • 4.11.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
4.9K
decreased by-7.65%
Maintainers
1
Weekly downloads
 
Created
Source

Master Build Status Develop Build Status Dependencies Dev Dependencies Known Vulnerabilities

Scramjet core

This is the minimal, dependency free version of scramjet used as of Scramjet version 3.0.0 as a base for scramjet and scramjet plugins.

Unless you are sure, you should be better off with using the main repo and module.

It is built upon the logic behind three well known javascript array operations - namingly map, filter and reduce. This means that if you've ever performed operations on an Array in JavaScript - you already know Scramjet like the back of your hand.

Usage

Scramjet uses functional programming to run transformations on your data streams in a fashion very similar to the well known event-stream node module. Most transformations are done by passing a transform function. You can write your function in three ways:

  1. Synchronous

Example: a simple stream transform that outputs a stream of objects of the same id property and the length of the value string.

   datastream.map(
       (item) => ({id: item.id, length: item.value.length})
   )
  1. Asynchronous using ES2015 async await

Example: A simple stream that uses Fetch API to get all the contents of all entries in the stream

datastream.map(
    async (item) => fetch(item)
)
  1. Asynchronous using Promises

Example: A simple stream that fetches an url mentioned in the incoming object

   datastream.map(
       (item) => new Promise((resolve, reject) => {
           request(item.url, (err, res, data) => {
               if (err)
                   reject(err); // will emit an "error" event on the stream
               else
                   resolve(data);
           });
       })
   )

The actual logic of this transform function is as if you passed your function to the then method of a Promise resolved with the data from the input stream.

API Docs

Here's the list of the exposed classes and methods, please review the specific documentation for details:

Note that:

  • Most of the methods take a callback argument that operates on the stream items.
  • The callback, unless it's stated otherwise, will receive an argument with the next chunk.
  • If you want to perform your operations asynchronously, return a Promise, otherwise just return the right value.

The quick reference of the exposed classes:

DataStream ⇐ stream.PassThrough

DataStream is the primary stream type for Scramjet. When you parse your stream, just pipe it you can then perform calculations on the data objects streamed through your flow.

 await (DataStream.fromArray([1,2,3,4,5]) // create a DataStream
     .map(readFile)                       // read some data asynchronously
     .map(sendToApi)                      // send the data somewhere
     .whenEnd());                         // wait until end

Detailed DataStream docs here

MethodDescriptionExample
new DataStream(opts)Create the DataStream.
dataStream.map(func, Clazz) ⇒ DataStreamTransforms stream objects into new ones, just like Array.prototype.mapmap example
dataStream.filter(func) ⇒ DataStreamFilters object based on the function outcome, just likefilter example
dataStream.reduce(func, into) ⇒ PromiseReduces the stream into a given accumulatorreduce example
dataStream.into(func, into) ⇒ DataStreamPushes the data into another scramjet stream while keeping flow control and
dataStream.use(func) ⇒ *Calls the passed method in place with the stream as first argument, returns result.use example
dataStream.tee(func) ⇒ DataStreamDuplicate the streamtee example
dataStream.each(func) ↩︎Performs an operation on every chunk, without changing the stream
dataStream.while(func) ⇒ DataStreamReads the stream while the function outcome is truthy.
dataStream.until(func) ⇒ DataStreamReads the stream until the function outcome is truthy.
dataStream.catch(callback) ↩︎Provides a way to catch errors in chained streams.
dataStream.raise(err) ⇒ PromiseExecutes all error handlers and if none resolves, then emits an error.
dataStream.pipe(to, options) ⇒ WritableOverride of node.js Readable pipe.
dataStream.bufferify(serializer) ⇒ BufferStreamCreates a BufferStreambufferify example
dataStream.stringify(serializer) ⇒ StringStreamCreates a StringStreamstringify example
dataStream.run() ⇒ PromiseConsumes all stream items without doing anything
dataStream.toArray(initial) ⇒ PromiseAggregates the stream into a single Array
dataStream.toGenerator() ⇒ Iterable.<Promise.<*>>Returns an async generator
dataStream.tap()Stops merging transform callbacks at the current place in the command chain.tap example
dataStream.whenRead() ⇒ Promise.<Object>Reads a chunk from the stream and resolves the promise when read.
dataStream.whenWrote(...data) ⇒ PromiseWrites a chunk to the stream and returns a Promise resolved when more chunks can be written.
dataStream.whenEnd() ⇒ PromiseResolves when stream ends - rejects on uncaught error
dataStream.whenDrained() ⇒ PromiseReturns a promise that resolves when the stream is drained
dataStream.whenError() ⇒ PromiseReturns a promise that resolves (!) when the stream is errors
dataStream.setOptions(options) ↩︎Allows resetting stream options.
DataStream.fromArray(arr) ⇒ DataStreamCreate a DataStream from an ArrayfromArray example
DataStream.fromIterator(iter) ⇒ DataStreamCreate a DataStream from an IteratorfromIterator example

StringStream ⇐ DataStream

A stream of string objects for further transformation on top of DataStream.

Detailed StringStream docs here

MethodDescriptionExample
new StringStream(encoding)Constructs the stream with the given encoding
stringStream.shift(bytes, func) ⇒ StringStreamShifts given length of chars from the original streamshift example
stringStream.split(splitter) ⇒ StringStreamSplits the string stream by the specified regexp or stringsplit example
stringStream.match(splitter) ⇒ StringStreamFinds matches in the string stream and streams the match resultsmatch example
stringStream.toBufferStream() ⇒ StringStreamTransforms the StringStream to BufferStreamtoBufferStream example
stringStream.parse(parser) ⇒ DataStreamParses every string to objectparse example
StringStream.SPLIT_LINEA handly split by line regex to quickly get a line-by-line stream
StringStream.fromString(str, encoding) ⇒ StringStreamCreates a StringStream and writes a specific string.

BufferStream ⇐ DataStream

A factilitation stream created for easy splitting or parsing buffers.

Useful for working on built-in Node.js streams from files, parsing binary formats etc.

A simple use case would be:

 fs.createReadStream('pixels.rgba')
     .pipe(new BufferStream)         // pipe a buffer stream into scramjet
     .breakup(4)                     // split into 4 byte fragments
     .parse(buf => [
         buf.readInt8(0),            // the output is a stream of R,G,B and Alpha
         buf.readInt8(1),            // values from 0-255 in an array.
         buf.readInt8(2),
         buf.readInt8(3)
     ]);

Detailed BufferStream docs here

MethodDescriptionExample
new BufferStream(opts)Creates the BufferStream
bufferStream.shift(chars, func) ⇒ BufferStreamShift given number of bytes from the original streamshift example
bufferStream.split(splitter) ⇒ BufferStreamSplits the buffer stream into buffer objectssplit example
bufferStream.breakup(number) ⇒ BufferStreamBreaks up a stream apart into chunks of the specified lengthbreakup example
bufferStream.stringify(encoding) ⇒ StringStreamCreates a string stream from the given buffer streamstringify example
bufferStream.parse(parser) ⇒ DataStreamParses every buffer to objectparse example

MultiStream

An object consisting of multiple streams than can be refined or muxed.

Detailed MultiStream docs here

MethodDescriptionExample
new MultiStream(streams, options)Crates an instance of MultiStream with the specified stream list
multiStream.streams : ArrayArray of all streams
multiStream.length ⇒ numberReturns the current stream length
multiStream.map(aFunc) ⇒ MultiStreamReturns new MultiStream with the streams returned by the tranform.map example
multiStream.find(...args) ⇒ DataStreamCalls Array.prototype.find on the streams
multiStream.filter(func) ⇒ MultiStreamFilters the stream list and returns a new MultiStream with only thefilter example
multiStream.mux(cmp) ⇒ DataStreamMuxes the streams into a single onemux example
multiStream.add(stream)Adds a stream to the MultiStreamadd example
multiStream.remove(stream)Removes a stream from the MultiStreamremove example

CLI

Check out the command line interface for simplified scramjet usage with scramjet-cli

$ sjr -i http://datasource.org/file.csv ./transform-module-1 ./transform-module-1 | gzip > logs.gz

License and contributions

As of version 2.0 Scramjet is MIT Licensed.

Help wanted

The project need's your help! There's lots of work to do - transforming and muxing, joining and splitting, browserifying, modularizing, documenting and issuing those issues.

If you want to help and be part of the Scramjet team, please reach out to me, signicode on Github or email me: scramjet@signicode.com.

Keywords

FAQs

Package last updated on 15 May 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc