forked from krulik/deploy-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (39 loc) · 1.03 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
'use strict';
let http = require('http');
let fs = require('fs');
let mongo = require('mongodb').MongoClient;
let url = process.env.MONGO_URL || '';
let db, collection;
let server = http.createServer();
server.listen(process.env.PORT);
server.on('request', handleRequest);
if (url) {
connectToMongo(url);
}
function connectToMongo(url) {
mongo.connect(url, (err, _db) => {
if (err) {
console.log(`got error=[${err}]`);
return;
}
db = _db;
console.log('Connected successfully to mongo', db);
collection = db.collection('items');
collection.find({data: 42}).toArray(function (err, docs) {
console.log(docs);
});
});
}
function handleRequest (request, response) {
if (request.url === '/' || request.url === '/index.html') {
fs.readFile('index.html', 'utf-8', (err, data) => {
response.end(data);
});
} else {
response.end(`Hi 2022 URL: ${request.url}, dbName: ${db.databaseName}`);
}
}
console.log(`listening on ${process.env.PORT}`);
module.exports = {
handleRequest
};