Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

326
Views
ts-node: normal generator doesn't work but async does in totally sychronous code

Today I was trying to build a simple generator that could loop over a directory of log files, and iterate through each file. Should be a relatively simple task? I ran into an issue with using generators, where using a normal one didn't work, but async did in totally synchronous code.

Am I missing something obvious, or is this a bug:

Here's the synchronous code.

// Assumes that the files and events within files are properly ordered
function* streamFromCache(dataDir, files) {
    Logger.info('Streaming file from cache');
    const files = fs.readdirSync(dataDir).sort();
    for(const file of files) {
        const logLines = JSON.parse(fs.readFileSync(`${dataDir}/${file}`));
        for(const logLine of logLines) {
            yield logLine;
        }
    }

const consumer = () => {
    ...
    console.log('before');
    for(const log of streamFromCache(dataDir, files) {
        console.log('test');
    }
    console.log('after')
}

output is just before, after, no logs in between

However is works when I change it to this:

// Assumes that the files and events within files are properly ordered
async function* streamFromCache(dataDir, files) {
    Logger.info('Streaming file from cache');
    const files = fs.readdirSync(dataDir).sort();
    for(const file of files) {
        const logLines = JSON.parse(fs.readFileSync(`${dataDir}/${file}`))['result'];
        for(const logLine of logLines) {
            yield logLine;
        }
    }

const consumer = async () => {
    ...
    console.log('before');
    for await (const log of streamFromCache(dataDir, files) {
        console.log('test');
    }
    console.log('after')
}

I get before, test, after as expected.

I'm using ts-node 10.4.0 and typescript 4.5.4.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!