我的配置类:ProjectDir / classes / config.js
'use strict';
class config{
getMongo(){
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:27017/nodedb', (err, database) => {
var db;
if (err) return console.log(err)
db = database;
console.log('Connected to mongo');
});
}
}
module.exports = config;
我的server.js文件(这里定义了所有路由):ProjectDir / server.js
console.log('May Node be with you');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
var configClass = require('./classes/config');//this is line 18
var config = new configClass();
错误:
SyntaxError: Invalid or unexpected token
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:588:28)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Module.require (module.js:568:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (D:\node\server.js:18:19)
[nodemon] app crashed - waiting for file changes before starting...
没有nodemon:
>node server.js
May Node be with you
D:\node\classes\config.js:1
(function (exports, require, module, __filename, __dirname) { ��'
SyntaxError: Invalid or unexpected token
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:588:28)
at Object.Module._extensions..js (module.js:635:
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Module.require (module.js:568:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (D:\node\server.js:18:19)
的package.json
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.2",
"ejs": "^2.5.7",
"express": "^4.16.2",
"mongodb": "^2.2.33",
"node-uuid": "^1.4.8",
"swagger-tools": "^0.10.3"
},
"devDependencies": {
"nodemon": "^1.12.1"
}
}
我是节点js的新手,我正在尝试使我的代码模块化,所以我创建了一个名为config.js的类,我想在我的索引文件中使用这个类,我的所有路由都写在这里。请帮忙!!
答案 0 :(得分:0)
在server.js中尝试此操作(未测试)
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
var { config } = require('./classes/config');//this is line 18
var config = new config();