Ways to quickly terminate a pipeline in a JavaScript transformation

Issue: I am facing a challenge with handling large files (>10GB). At times, I need to process the entire file while other times I only need to sample a few lines.

The processing mechanism involves a pipeline:

        pipeline(
            inStream,
            split2(),
            sc,
            err => {
                 ...
            }
        );

sc is a transformation that primarily counts specific flags in the file.

Everything works smoothly when processing the complete file, however, it fails to generate output if I try to exit the transformation before inStream completion.

        _transform(chunk, encoding, done) {
        let strChunk = decoder.write(chunk);
        if(strChunk === '\u0003') {
            this.push('\u0003');
            process.exit(0;
        }
        if (strChunk.startsWith("@")) {
            done();
        } else {
            if (this.sampleMax === 0) {
                this.push('\u0003');
            } else if (this.sampleMax > 0) {
                this.sampleMax--;
            }
            let dta = strChunk.split("\t");
            let flag = dta[1].trim();
            this.flagCount[flag]++;
            done();
        }

Using //process.exit(0), prevents reaching the code following sc in the pipeline. On the other hand, solely utilizing this.push('\u0003'); results in processing the full inStream.

The main dilemma is how to correctly end the transform and proceed with the downstream pipeline without thoroughly reading inStream.

Answer №1

There are two possible approaches to handling an error in this scenario: either by throwing an error explicitly or implicitly creating one by terminating the stream. The code snippet below demonstrates both options.

_transform(chunk, encoding, done) {
    let strChunk = decoder.write(chunk);
    if (strChunk === '\u0003') {
        this.push('\u0003');
        process.exit(0);
    }
    if (strChunk.startsWith("@")) {
        done();
    } else {
        if (this.sampleMax === 0) {
            // Either of the following lines can resolve the issue.
            throw("PLANNED_PREMATURE_TERMINATION");
            this.destroy(); // => Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close
        } else 
            if (this.sampleMax > 0)
                this.sampleMax--;
        let data = strChunk.split("\t");
        let flag = data[1].trim();
        this.flagCount[flag]++;
        done();
    }

The next step involves responding to errors that occur within the pipeline in reaction to the above code.

    pipeline(
        inStream,
        split2(),
        sc,
        err => {
             if (err && (err === "PLANNED_PREMATURE_TERMINATION") || 
               (err === "Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close") {
                 // Implement actions for this specific error case
             } else {
                // Stream processing completed successfully
                // Implement actions for this case
             }
        }
    );

By utilizing the message contained in err regarding the premature termination, we can handle and display the partially aggregated data in sc. This solution effectively addresses the initial problem and appears to be the most suitable course of action. As such, I am sharing this solution, although more elegant alternatives would be highly appreciated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Conceal flexbox item depending on neighboring element dimensions or content

I've encountered an issue while using a flexbox to display two elements side by side. The left element contains text, while the right one holds a number. When the value in the right element has at least 7 digits ( > 999,999 or < -999,999), I ne ...

How to Display Prices in Euros Currency with Angular Filter

Can someone help me figure out how to display a price in euros without any fractions and with a dot every 3 digits? For example, I want the price 12350.30 to be shown as 12.350 €. I attempted to use the currency filter but it only worked for USD. Then ...

Steps for creating a herringbone design on an HTML canvas

Seeking Help to Create Herringbone Pattern Filled with Images on Canvas I am a beginner in canvas 2d drawing and need assistance with drawing mixed tiles in a cross pattern (Herringbone). var canvas = this.__canvas = new fabric.Canvas('canvas' ...

The two CSS classes are styled with different border-color values, but only one is being applied correctly

My goal is to modify the border color of a textarea using jQuery. Previously, I achieved this by using .css("border-color","rgb(250,0,0)"), and it was working perfectly. However, I have now been advised against using CSS directly in JavaScript and told to ...

What is the best way to automatically log out a user when a different user logs in on the same browser?

Currently, I am encountering an issue where there are two separate dashboards for different types of users - one for admin and the other for a merchant. The problem arises when an admin logs in on one tab and then a merchant logs in on another tab in the s ...

When encountering an "uncaught SyntaxError" in the $.parseJSON function, one may want to investigate

When using this jQuery function, I encounter an Uncaught SyntaxError: Unexpected token u error if the cookie $.cookie('chk_ar') is undefined. function checkBgNoise() { // checks background noise option state, // activates 'on' click i ...

My Discord.js bot was running smoothly until I added a new command, and suddenly everything went haywire. Can someone assist me in figuring out what went

I recently delved into the world of creating discord bots by following a simple tutorial and customizing it to suit my needs. Initially, the bot worked perfectly fine. However, when I attempted to add the "Mistake" command, it stopped functioning properl ...

Update all field values in Redux-form version 6.0 and above

I am attempting to update several values in redux-form. They are stored in a single object, and I want to replace the current redux-form state values with those from my object. One method I have tried involves using this.props.reset() followed by multipl ...

Incorporate a JavaScript array into a TypeScript document

Having a file named array.js with a large collection of strings, structured like this: module.exports = ["word1","word2",...] I attempted to utilize this array in my validation.ts file by adding the following line: let wiki = require('./array.js&a ...

Different approach for binding in Vue.js

Seeking Alternatives I am curious to find out if Vue.js offers a different approach for outputting data beyond the conventional curly braces. Is there a syntax similar to Angular's ng-bind directive that I could utilize? Although Vue.js primarily ut ...

How about: "Add random HTML content using jQuery each time the page is refreshed

Currently facing this issue: I implemented a jquery plugin fullPage.js by Alvaro Trigo on my website. The plugin script automatically inserts the html structure in certain elements... in my html I have: <div class="section fp-auto-height-responsive" ...

Transferring data from a class method to a React component

Situation: In a React component, I have a class with its own methods that is instantiated. What I'm needing: One of the methods in the class changes the value of an input (referred to as `this.$el`) using `.val()`. However, I need to pass this value ...

The property 'join' is undefined for null values

I've recently started learning AngularJS, but I'm having trouble figuring out what's causing issues in my code. Despite trying various approaches, the outcome is always incorrect. <!DOCTYPE html> <html lang="en" ng-app="myApp"> ...

Ways to extract certain characters from each element in an array

I'm attempting to make the first four characters of each element in an array (specifically a list) bold, but I am only able to select entire strings: $("li").slice(0).css("font-weight", "Bold"); Is there a way for me to indicate which characters wit ...

Having trouble verifying a phone number using the awesome-phonenumber npm package?

I recently developed some JavaScript using the awesome-phonenumber npm package. index.js const yargs = require('yargs'); var PhoneNumber = require( 'awesome-phonenumber' ); const argv = yargs .usage('Usage: $0 -n [num]' ...

Switch up the text within the URL of the background image

Simply put, this is the structure I have: <div id="RelatedPosts1"> <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-1.jpg)"></div> <div class="related-posts-thumb" style="background: url(http: ...

Utilizing jQuery Functions on Dynamically Generated Items within a Chrome Extension

My Chrome extension is running jQuery smoothly, except for dynamically created elements. It triggers an error message that reads: Refused to execute JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self& ...

Filtering objects in AngularJS is a complex task, especially when you need to be able to search for a specific value but also consider if that value exists

Struggling to convey my thoughts in English, but here it goes. Imagine two objects linked by colorid: $scope.fruits = {{name:"apple",colorid:"1"},etc}; $scope.colors = {{id:"1",value:"red"}; I've created a table with search and filter function ...

Provide Chai/Mocha with a selection of essential keys that need to be incorporated

It appears that running the following code: describe( 'Add Youtube', function () { it( 'should return the video data, including user, title and content fields', function ( done ) { this.timeout( 5000 ) request({ ...

AngularJS: The requested resource does not have the "Access-Control-Allow-Origin" header

Currently developing my web application using AngularJS, I have a file named script.js which contains the following code: var module = angular.module('project', ['ngRoute']); // setting up our routes module.config(function ($r ...