最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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"
  ]
}
发布评论

评论列表(0)

  1. 暂无评论