Hold on for the processing of a CSV document

I am attempting to utilize the "csv-parse" library in Typescript to read a csv file by creating an observable. The code provided uses fs.createReadStream to read the file. I am looking to return the observable and subscribe to it, but it seems that the process is not retrieving anything, potentially due to not properly awaiting the asynchronous fs.createReadStream. How can I resolve this issue?

import { parse } from "csv-parse";
import { Observable } from "rxjs";
import * as fs from "fs";
import path from "path";

export interface StdJsonDoc<T = string> {
  [key: string]: T;
}

export function createCsvObservable(
  filePath: string,
  fileType: string | undefined = undefined,
  fieldDelimiter: string = ",",
  columnHeader: boolean = true
) {
  if (fileType !== "csv") {
    throw Error(`Cannot create CSV observable from non CSV file`);
  }

  return new Observable<StdJsonDoc>((subscriber) => {
    const parser = fs.createReadStream(filePath).pipe(
      parse({
        delimiter: fieldDelimiter,
        columns: columnHeader,
        trim: true,
        skip_empty_lines: true,
        relax_column_count: true,
      })
    );

    parser.on("readable", () => {
      let record: StdJsonDoc;
      while ((record = parser.read())) {
        subscriber.next(record);
      }
    });
    parser.on("end", () => {
      subscriber.complete();
    });
    parser.on("error", () => {
      subscriber.error();
    });
  });
}

async function start() {
  const myObservableCsv = createCsvObservable(
    path.join(__dirname, "data", "myCsvFile.csv"),
    "csv"
  );
  myObservableCsv.subscribe({
    next: (record) => {
      console.log(`RECORD: ${record}`);
    },
    error: () => {
      console.log("ERROR");
    },
    complete: () => {
      console.log("COMPLETE");
    },
  });
}

start().then(() => {
  console.log(`*** END PROGRAM ***`);
  process.exit(0);
});

Answer №1

The recipient of the call does not sign up for the observable that is returned. What will occur if you execute the following code:

createCsvObservable(path.join(__dirname, "data", "myCsvFile.csv"),"csv").subscribe(console.log);

Answer №2

After some troubleshooting, the issue was identified as the use of an "asynchronous" main function. By removing the "async" keyword and calling the main function directly, the problem was resolved.

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

The Dialog feature offered by jQuery-UI

Having just started with jQuery, I am looking to implement the jQuery-UI Dialog to display a message containing lengthy text to the user. My goal is to have a "More details" link in each row of my HTML table that will trigger the jQuery Dialog window to op ...

"Displaying 'Object Object' as a title when hovering over an element

I am currently using an accordion element to display several FAQs on a webpage. The code snippet for the accordion with content is as follows: { Object.keys(FAQS).map((key, index) => { return ( <div key={key}> ...

Unable to generate a fresh directory with mongoose and express

As the title suggests, I am working on an application that generates a link using mongoose _id and express's app.get when certain information is inputted. However, I am facing an issue where I have to reload the entire server in order to access the di ...

"Enhance Your WordPress Website with the Power of jQuery

I have been developing a unique Wordpress plugin that incorporates a grid loading effect using jQuery. The script I have implemented is as follows: <script type="text/javascript"> new GridScrollFx( document.getElementById( 'grid' ), { ...

Tracking changes in real time and calculating the sum with AJAX, PHP, and MySQL for efficient processing

Initially, I kindly request you to read this until the end. I am in dire need of assistance with my problem as I have searched for solutions but still remain clueless. https://i.sstatic.net/DAb1q.png Referring to the image provided, the first 'Produ ...

JavaScript Magic: Hide Div when Clicking Away

I need a solution where clicking outside of the My DIV with the ID Container_ID will hide all elements within the Container by setting their style to display: none;. Currently, the JavaScript code I am using partially achieves this functionality, but it al ...

What is the simplest method to create a scroller for engaging narratives?

I am in the process of creating a static but responsive storytelling website using HTML. My objective is to create an effect similar to this: https://i.stack.imgur.com/zIEpU.gif The idea is to have text on the left and a *.jpg image fixed on the right. As ...

A step-by-step guide on uploading a file to an AWS S3 bucket using a pre-signed URL in a Node

I am currently using S3 upload function in Node.js to upload files to an S3 bucket. The frontend of the application is built on Angular. However, my client now requires that all uploads be directed to the S3 bucket via a presigned URL. I am wondering if th ...

Ways to conceal a grid item in Material UI framework

My goal is to hide a specific grid item for a product and smoothly slide the others in its place. Currently, I am using the display:none property but it hides the item instantly. I have already filtered the products and now I want to animate the hiding of ...

sum inside the while loop

Below is the provided HTML: <form> <textarea id="input1"></textarea> <textarea id="input2"></textarea> <span></span> </form> The following JavaScript code is included: $("#input2").keyup{ var a = ...

Having trouble with the post request in Express JS and Vue? Don't worry, we've got you covered

I've been following a tutorial to set up a basic app and everything is working smoothly, except for the post request which seems to be causing me trouble. Tutorial: https://www.youtube.com/watch?v=HkIGAqAP1GY Although the issue is reproducible based ...

An issue has occurred while trying to execute the npm start command within PhpStorm

When I try to run npm start on Windows' command prompt, it works fine. However, I encounter errors when running it in the PhpStorm Terminal. You can see the errors here. Is this a result of them being different platforms or could it be related to som ...

Stopping the ability to navigate within an Ionic application

I am attempting to block navigation and display a popup in a controller. $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { if(someConditionMet) { event.preventDefault(); showPopup(); } } ...

Having trouble configuring a basic express server to host a static JavaScript file

Struggling to set up a basic Express server with accompanying HTML and JS files. Despite multiple attempts, I can't get the JS file to properly load. index.js: const express = require("express"); const app = express(); const path = require ...

When getStaticPaths and getStaticProps are programmed to deliver results

Seeking assistance with my first attempt at using getStaticPaths and getStaticProps in nextJS as a beginner. Can anyone help me resolve this issue? const datas = [ { id: 1, name: "Banheiro", image: "https://res.cl ...

Leveraging AWS CDK to seamlessly integrate an established data pipeline into your infrastructure

I currently have a data pipeline set up manually, but now I want to transition to using CDK code for management. How can I achieve this using the AWS CDK TypeScript library to locate and manage this data pipeline? For example, with AWS SNS, we can utilize ...

Experiencing delays with Angular 4 CLI's speed when running ng serve and making updates

After running ng serve, I noticed that the load time is at 34946 ms, which seems pretty slow and is impacting our team's performance. Additionally, when we update our code, it takes too long to reload the page. https://i.sstatic.net/lpTrr.png My Ang ...

Retrieving ng-repeat object in Angular

How can I retrieve the current object from an ng-repeat on ng-click without using $index? The $index method is giving me the wrong index due to my use of orderBy. Ideally, I would like to be able to click on the object (thumbnail) and have $scope.activePer ...

Error 404: Angular 2 reports a "Not Found" for the requested URL

I am currently in the process of integrating an Angular 2 application with a Java Spring Boot backend. As of now, I have placed my Angular 2 files under src/main/resources/static (which means that both the Angular and Spring apps are running within the sam ...

How to efficiently await multiple promises in Javascript

My Objective: Collect artist IDs Find them in the database Create new ones if needed Create an event record in the database and obtain its ID Ensure all artist IDs and event ID are gathered before proceeding Loop through combin ...