1

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?

3
  • Run your main script with the --experimental-worker flag: like this: node --experimental-worker your_main_script.js . but also you didn't share your full main script because you can create and run the worker thread: Commented Nov 16, 2023 at 11:24
  • i update the code now please check it & i also tried the solution that you provided.it didn't work as well Commented Nov 16, 2023 at 12:25
  • 1
    You have 2 choices. Either name all your files .mjs instead of .js or add "type": "module" in package.json Commented Nov 17, 2023 at 3:28

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

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.