1

I need to use worker_threads in Nodejs (server side question only) + Typescript.

I tried the following without success:

scripts/worker.ts

import { parentPort, workerData } from 'worker_threads';

if (parentPort) {
    console.log(workerData);
}

scripts/start.ts - main entry point

import os from 'os';
import path from 'path';
import { Worker } from 'worker_threads';

(async () => {
    await start();
})();

async function start() {
    const numWorkers = os.cpus().length;
    console.log(numWorkers);

    const worker = new Worker(path.resolve(__dirname, 'worker.ts'), {
        workerData: { config: { a: 'b' }, historicalData: [2, 4] },
    });

    worker.on('message', value => {
        console.log(value);
    });
    worker.on('error', err => {
        console.error(err);
    });
    worker.on('exit', code => {
        if (code !== 0) throw new Error(`Worker stopped with exit code ${code}`);
    });
}

I run the script like ts-node scripts/start.ts and get error

import { parentPort, workerData } from 'worker_threads';
^^^^^^

SyntaxError: Cannot use import statement outside a module

This is my tsconfig.json

{
  "compilerOptions": {
    "esModuleInterop": true,
    "preserveConstEnums": true,
    "strict": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "allowJs": true,
    "target": "es2015",
    "outDir": ".build",
    "moduleResolution": "node",
    "lib": ["es2015"],
    "rootDir": "./"
  },
  "include": [
    "./src"
  ]
}
4
  • 1
    Your package.json needs to have "type": "module" Commented Mar 12 at 10:41
  • ts-node is known to have issues with native esm, stick to tsx instead Commented Mar 12 at 10:47
  • 1
    @clxrity I added "type": "module", to package.json and now ts doesn't compile. Says unknown file extension .ts Commented Mar 12 at 10:55
  • This issue comment seems potentially-relevant (but I don't know if anything has changed since it was written in 2019). Commented Aug 24 at 11:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.