How to use ES6 import in worker thread in Node.js?

417 views Asked by At

How to use ES6 import in worker thread?

I'm trying to utilize ES6 import syntax in a worker thread in a Node.js environment. However, I'm encountering issues with the import statement. Here's a simplified version of my code: app.js

import express from 'express'
import bodyParser from 'body-parser'
import os from 'os'
import { Worker } from 'worker_threads'

const app = express()
const router = express.Router()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use('/api', router)
router.get('/worker-thread', (req, res) => {
  const worker = new Worker('./worker_thread/index.js')
  worker.on('message', (j) => {
    return res.status(200).json({ value: j, message: 'running successfully' })
  })
})
app.listen(4000, () => {
  console.log('PORT RUNNING ON 4000')
})

worker_thread.js

import { parentPort } from 'worker_threads';

let j = 0;

for (let i = 0; i < 5000000000; i++) {
  j++;
}

parentPort.postMessage(j);

Running this code results in a SyntaxError: Cannot use import statement outside a module. I want to leverage ES6 features within the worker thread. What's the correct way to achieve this without transpiling the code?

1

There are 1 answers

0
LmanTW On

I tried to run your code, it run successfully with no problem, the url return {"value":1000,"message":"running successfully"} (I change the loop for testing)

File Structure:

app.js

worker_thread

|child_thread.js

package.json

package.json:

{
  "type": "module",
  "dependencies": {
    "body-parser": "^1.20.2",
    "express": "^4.18.2"
  }
}

I'm guessing that maybe in your worker_thread/child_thread.js node.js couldn't find your package.json to know it's using ES6, please tell me if I did something wrong when trying to reproduce this error :D