-3

I have the following Node.js program that runs through text and outputs the top 25 most frequently used words basically. I need to follow a certain style and everything seems right but I get the following error with the await keyword when I run the program:

` for await (const chunk of stream) { ^^^^^

SyntaxError: Unexpected reserved word at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18) at ESMLoader.moduleProvider (node:internal/modules/esm/loader:468:14) at async link (node:internal/modules/esm/module_job:67:21)`

Here is the full code below:

` const fs = require('fs');

    const stopwords = new Set(fs.readFileSync('../stop_words.txt').toString().split       (',').concat(Array.from({ length: 26 }, (_, i) => String.fromCharCode(i +       97))));

    function* characters(filename) {
      const stream = fs.createReadStream(filename, { highWaterMark: 1024 });
      for await (const chunk of stream) {
        for (const c of chunk) {
          yield String.fromCharCode(c);
        }
      }
    } 

    function* all_words(filename) {
      let word = '';
      for (const c of characters(filename)) {
        if (/\w/.test(c)) {
          // We found the start or middle of a word
          word += c.toLowerCase();
        } else if (word) {
          // We found the end of a word, emit it
          yield word;
          word = '';
        }
      }
      if (word) yield word; // Emit the last word
    }

    function* non_stop_words(filename) {
      for (const w of all_words(filename)) {
        if (!stopwords.has(w)) {
          yield w;
        }
      }
    } 

    function* count_and_sort(filename) {
      const freqs = {};
      let i = 1;
      for (const w of non_stop_words(filename)) {
        freqs[w] = freqs[w] + 1 || 1;
        if (i % 5000 === 0) {
          yield Object.entries(freqs).sort((a, b) => b[1] - a[1]);
        }
        i++;
      }
      yield Object.entries(freqs).sort((a, b) => b[1] - a[1]);
    } 
    `

I couldn't find a solution to this error for my particular situation. Please help me fix my usage of await here specifically to get my program running.

Adam Wolf
  • 1
  • 2
  • when in doubt, refer to [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) – Jaromanda X Feb 25 '23 at 04:33

1 Answers1

0

You can only use await inside an async function (or the top level of a module).

async function* characters(filename)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80