node.js - How to use NodeJS worker_threads with typescript? - Stack Overflow

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

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"
  ]
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744758298a4592014.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信