【问题标题】:Got this error when trying to run node server [duplicate]尝试运行节点服务器时出现此错误[重复]
【发布时间】:2018-01-25 10:30:20
【问题描述】:

我正在使用 Linux mint。我的node版本是9.4,nmp版本是5.6

查看我在运行“节点服务器”时遇到的错误

/var/www/html/mean/firstapp/server.js:1
(function (exports, require, module, __filename, __dirname) { import mongoose from 'mongoose';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at new Script (vm.js:51:7)
    at createScript (vm.js:138:10)
    at Object.runInThisContext (vm.js:199:10)
    at Module._compile (module.js:624:28)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at startup (bootstrap_node.js:193:16)

通常我从 MongoDB 收到此错误

MongoDB shell version v3.6.2
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 3.6.2
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
    http://docs.mongodb.org/
Questions? Try the support group
    http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] 
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] 
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] 
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] 
2018-01-31T11:25:28.254+0530 E -        [main] Error loading history file: FileOpenFailed: Unable to fopen() file /home/ranjit/.dbshell: No such file or directory

【问题讨论】:

    标签: node.js


    【解决方案1】:

    节点本身不支持导入,也称为 ES 模块。 Node 默认使用 CommonJS (require)。

    Node 9 现在确实支持 ES 模块,但它有一个标志。[1]

    要将 server.js 与 ES 模块一起使用,您需要将其重命名为 server.mjs 并像这样启动它:

    node --experimental-modules server.mjs

    [1]https://nodejs.org/api/esm.html

    【讨论】:

    • 当我尝试这个时它仍然给出错误。我将 server.js 重命名为 server.mjs 并运行上面写的命令
    • 错误是什么
    【解决方案2】:

    import 不支持 Node 中 CommonJS 模块系统的语法。

    您可以使用require,也可以使用babel-node 之类的东西转译您的Node.js 代码。

    https://babeljs.io/docs/usage/cli/#babel-node

    【讨论】:

    • 我应该更改所有写入 import 的文件吗?
    • 是的,你应该,或者使用 babel。阅读链接的文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多