node.js - Javascript,使用 require() 并在同一个文件中导入

标签 node.js node-modules

我需要在我的文件中使用 require() 以便我可以使用“readline”,但我还需要使用 import 以便我可以使用模块。但是当我在模块内部使用 require 时,它​​会显示 要求未定义 .这是代码:

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

如何在模块中使用 require() 和导入,或者有其他方法可以解决这个问题?

最佳答案

我建议你使用 import而不是 require()如果您已经在 require() 之后的 ESM 模块文件中仅存在于 CJS 模块中,而不存在于 ESM 模块中。这是一个有效的代码示例:

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();
});

在 Node v12.13.1 中,我使用以下命令行运行它:
node --experimental-modules temp.mjs

仅供引用,从您的评论来看,您似乎跳过了 .createInterface()步。

关于node.js - Javascript,使用 require() 并在同一个文件中导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61923956/

相关文章:

java - 树结构中的递归回溯

javascript - 从 vue-cli 应用程序中的 node_modules 导入 js 文件

Javascript 打印 node.js 版本和模块版本

reactjs - babel JS文件无法解析 "@babel/runtime/helpers/builtin/classCallCheck"

javascript - 找不到模块 : internal/modules/cjs/loader. js:969

node.js - 如何在 TypeScript npm 模块中导出类型

linux - 在位置 2 安装带有 NVM 不匹配支架的 NPM

javascript - ReferenceError : window is not defined at object. <匿名> Node.js

node.js - 努力让回调工作express.js

node.js - 使用 Node.js 创建 google 云存储对象的 SignedURL