尝试运行节点服务器时出现此错误

时间:2018-01-25 10:30:20

标签: node.js

我正在使用Linux mint。我的节点版本是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

2 个答案:

答案 0 :(得分:1)

节点中的CommonJS模块系统不支持

import

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

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

答案 1 :(得分:1)

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

节点9现在支持ES模块,但它位于标志后面。[1]

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

node --experimental-modules server.mjs

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