Navigating the contents of the text file using TypeScript

After locating the file flight.txt, I have obtained the following flight information:

1 DFW BOM 2016-05-20 12:20 2016-05-21 02:40 1084.00 JetAirways 100
2 DFW DEL 2016-04-24 17:15 2016-04-25 07:20 1234.00 Lufthansa 100
3 DFW FRA 2016-06-05 13:30 2016-06-05 03:32 674.00 AmericanAirlines 100

The provided code demonstrates how to read a file in typescript:

 populateFlightList() {
   let data = fs.readFileSync('flight.txt').toString('utf-8'); {
        let textByLine = data.split("\n")
        console.log(textByLine);

    };

I am now looking to iterate through the file, extract the necessary data and convert it into flight objects by creating new objects and adding them to an array list.

   try {
        Scanner fin = new Scanner(file);                
        while(fin.hasNext()) {
          int number = fin.nextInt();                 // Flight number
          String from = fin.next();                   // Departure airport
          String to = fin.next();                     // Arrival airport
    }**Code in Java**

Is there a similar way to achieve this functionality in TypeScript?

Answer №1

If you want to read data from a file one line at a time, you can utilize the readline module in Node.js. However, keep in mind that parsing the data will require manual effort. Here's a sample code snippet:

import * as fs from 'fs';
import * as rd from 'readline'

var reader = rd.createInterface(fs.createReadStream("W:\\tmp\\stack\\2\\data.txt"))

var data: Array<{ number: number; from: string; to: string}> = [];
reader.on("line", (l: string) => {
    var tokens = l.split(' ');
    var nr= parseInt(tokens[0]);
    var from = tokens[1];
    var to = tokens[2]
    console.log(`nr: ${nr} from ${from} to ${to}`);
    data.push({
        number: nr, from, to
    });
})
console.log(`The data array is currently empty because data has not been read yet: ${data.length}` );

reader.on("close", ()=> {
    console.log(`Data has been successfully read. Total entries: ${data.length}` );
    data.forEach(element => {
        console.log(`nr: ${element.number} from ${element.from} to ${element.to}`)
    });
})

The line event will be triggered for each line of the file being read. The close event, on the other hand, will signal that the entire file has been read and closed, making the complete dataset available for processing. Remember, you are building up your data set one entry at a time every time the line event occurs.

To learn more about the readline module, refer to the official documentation.

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

Refresh the navigation bar on vuejs post-login

Creating a client login using Vue has been a challenge for me. My main component includes the navigation bar and the content rendering component. The navigation component checks if the user is logged in to display the buttons for guests and hide the button ...

Display elements in an array of objects when the value changes with React

In my code, I am working with a nested list where each element has child nodes including id, name, and ancestors. The ancestors node contains an array of names and ids of the parent node, grandparent node, and so on. Here is an example: { "name": "Chi ...

Display the matrix in a semi-spiral pattern

I am working with a 3 by 5 matrix, filled with numbers from 1, presented as follows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 The task is to print the values in a half-spiral order, starting from the bottom left vertically: 11 6 1 5 10 15 12 7 2 4 9 ...

Tips for resolving the issue of encountering the error message "Cannot POST /" while transitioning between different websites

Forgive my lack of knowledge, I'm still in the learning process :) I am attempting to navigate from an HTML website to a React-built website by clicking a button. The first website is a simple HTML page, while the destination website is more complex a ...

Having trouble transferring data from JavaScript to PHP via POST method

Hi there, this is my first time posting and I could really use some assistance. I have a bit of a roadblock with two Symfony forms on a page that don't seem to be working properly. The first form is for a contract, while the second one is used to pop ...

(Discord.JS) Bot failing to send direct message upon user joining the server

When attempting to send a DM message, I am using the following code: bot.on('guildMemberAdd', (member) => { member.send('a'); }); I am experiencing difficulty in understanding why the private message is not being successfully se ...

What is the best way to manage the retrieved data in a situation where I am utilizing async-await along with the useEffect hook?

I need to retrieve a player's statistics based on the input provided by the user, and then show it. I am facing challenges in storing the retrieved data using the useEffect hook. Any suggestions for a more efficient approach? import React, { useEf ...

Is it possible to call a function directly from useEffect?

Code VersionA: useEffect(() => doRequest(), []); Code VersionB: useEffect(() => { doRequest(); }, []); I used to believe that both versions were the same, with VersionA being a shortcut and VersionB allowing for multiple commands within the inlin ...

To validate any object, ensure that it contains a specific key before retrieving the corresponding value in typescript

When looking at a random object, my goal is to verify that it follows a certain structure. obj = {WHERE:{antherObject},OPTIONS{anotherObject}} Once I confirm the object has the key using hasProperty(key), how can I retrieve the value of the key? I thoug ...

AngularJS anticipates the completion of a lone asynchronous request

Attempting to assign data to the scope after an asynchronous call. There is an array named companies in the factory. factory.getByCategoryId = function (id) { $http.get('http://localhost/campaign?access-token=12345&id=2').then( func ...

Using Vue to change select box data separately

I have a functional select box that is currently sending the selected value to a method when the change event occurs. However, I am wondering about something: Let's say I also want to send the cat_id value at the time of selection (to create an objec ...

Retrieving URL parameters within an API route handler in Next.js

Within my client component called GetUserInfoButton, I initiate a GET request using the URL format of http://localhost:3000/test/users/[id]. The [id] in this URL is represented by an alphanumeric sequence similar to MongoDb. My intention within the file a ...

What could be causing this conflicting behavior with the logical "and" operator?

const {DEMO, PORT, LOCAL} = process.env; const socketAddress = (DEMO & LOCAL)? `http://${hostname}:${PORT}`: `wss://${hostname}`; When DEMO is false, PORT is undefined, and LOCAL is true The hostname being used is http://9f9cbf19.ngrok.io I verified ...

The callback function inside the .then block of a Promise.all never gets

I'm currently attempting to utilize Promise.all and map in place of the forEach loop to make the task asynchronous. All promises within the Promise.all array are executed and resolved. Here is the code snippet: loadDistances() { //return new Prom ...

evt.target consistently returns the initial input within the list of inputs

My React file uploader allows users to attach multiple file attachments. Each time a user clicks on an input, I retrieve the data-index to identify the input position. renderFileUploader() { let file_attachment = this.state.file_attachment.map(fun ...

The React-router component fails to refresh when navigating using the <Link> element

Recently, I have encountered a problem while trying to use a <Link> element to navigate between routes and update components. Although the path in my application changes in the redux store upon clicking the link, the component fails to update. It see ...

Mongoose - Child Subdocument with References to Parent Schema

Could a Mongoose Schema be structured similar to this example: var categorySchema = new Schema({ name : String }); var childSchema = new Schema({ name : String, category : { type : Schema.Types.ObjectId, ref : 'parent.categori ...

Self-contained VUE app

Can Vue.js be built as a standalone application so that I am not reliant on backend services from my web hosting provider? In essence, I would like to avoid having to start up the app through npm and instead simply open the index.html file from the dist f ...

Ensure that the input field retains its content after submission in an AngularJS application

HTML <form ng-controller="updatecontroller" ng-submit="updateUser()"><label class="control-label">First Name</label> <input type="text" ng-model="user.userFirstName"> <label class="control-label">Last Name</label& ...

Steps for detecting a 401 Unauthorized error in SignalR when the token has expired

I have created a dynamic page that continuously fetches real-time information from my Azure functions backend using SignalR. If I am on the page for an hour and experience a disconnect, the signalr client will attempt to reconnect automatically, which usua ...