DeceivedRiver
DeceivedRiver

Reputation: 141

Javascript, using require() and import in the same file

I need to use require() in my file so I can use 'readline', but I also need to use import so I can use a module. But when I use require inside of my module it says require is not defined. Here is the code :

var r1 = require('readline')
import car from './carclass.mjs'
var input = ""
var questionToAsk = ""
const question1 = () => {
    return new Promise((resolve, reject) => {
        r1.question(questionToAsk, (answer) => {
            input = answer
            resolve()
        })
        r1.question()
    })
}
const main = async () => {
    console.log("What is the Brand?")
    await question1()
    var brandName = input
    console.log("What is the Model?")
    await question1()
    var modelName = input
    console.log("What is the Speed?")
    await question1()
    var carSpeed = input
    var newCar = new car(brandName,modelName,carSpeed)

    r1.close()
}
main()

How can I use require() and import in a module, or is there some other way I can approach this?

Upvotes: 9

Views: 10183

Answers (3)

Sachin Singh
Sachin Singh

Reputation: 31

import { createRequire } from "module";
const require = createRequire(import.meta.url);

Use this code on the top of the file in which you want to use 'IMPORT' and 'Require' both

Upvotes: 3

ISMAIL BOUADDI
ISMAIL BOUADDI

Reputation: 343

to use import and require() you can try this

import { createRequire } from "module";
const require = createRequire(import.meta.url);

Upvotes: 4

jfriend00
jfriend00

Reputation: 708146

I'd suggest you just use import instead of require() if you're already in an ESM module file since require() only exists in CJS modules, not ESM modules. Here's a code example that works:

import readline from 'readline';
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("What's up?\n", data => {
    console.log(`Got your result: ${data}`);
    rl.close();
});

In node v12.13.1, I run this with this command line:

node --experimental-modules temp.mjs

FYI, from your comments, it appears you were skipping the .createInterface() step.

Upvotes: 2

Related Questions