'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?
Solution 1:[1]
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.
Solution 2:[2]
to use import and require() you can try this
import { createRequire } from "module";
const require = createRequire(import.meta.url);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jfriend00 |
Solution 2 | ISMAIL BOUADDI |