loop over a file line by line and separate by multiple spaces in typescript

To loop over a file line by line and separate by multiple spaces in TypeScript, you can use the built-in fs module to read the file and a regular expression to split the string into an array of words. Here's an example:

index.ts
import * as fs from "fs";

const filePath = "path/to/your/file.txt";
const regex = /\s+/;

const readStream = fs.createReadStream(filePath);

readStream.on("data", (chunk: Buffer) => {
  const lines = chunk.toString().split("\n");
  for (const line of lines) {
    const words = line.trim().split(regex);
    // do something with the words
  }
});

readStream.on("end", () => {
  console.log("Finished reading the file");
});
426 chars
19 lines

In this example, we first define the path to the file and a regular expression that matches multiple spaces. We then create a read stream using the createReadStream method from the fs module. We listen to the 'data' event, which is emitted each time the stream receives a chunk of data. Here, we split the chunk into lines using the split method on a string and iterate over each line. We trim the line to remove any leading or trailing white space and split it into words using the regular expression we defined earlier. Finally, we can do something with the words, such as push them to an array or perform some sort of analysis on them.

Once the read stream has finished reading the file (emitting the 'end' event), we print a message to the console to indicate that we've finished reading.

gistlibby LogSnag