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条)