-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
49 lines (43 loc) · 1.36 KB
/
server.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
46
47
48
49
var fs = require('fs');
var express = require('express');
var nano = require('nano')('http://localhost:5984'); // Connect to the CouchDB running on port 5984
var app = express();
var db_name = 'test'; // The name of the database to connect to
var db = nano.use(db_name);
function insertDoc(doc, tried){
db.insert(doc, function(err, http_body, http_headers){
if(err){
if(err.message === 'no_db_file' && tried < 1){
return nano.db.create(db_name,function(){
insert_doc(doc, tried+1);
});
} else {
return console.log(err);
}
}
});
}
// Populate the `test` database with data from `test_data.json`
fs.readFile('./test_data.json',function(err, data){
var aData = JSON.parse(data);
for (var n = 0; n < aData.length; n++){
insertDoc(aData[n],0);
}
});
// Start the server
var server = app.listen(3000, function () {
var port = server.address().port;
console.log('Example app listening at http://localhost:%s', port);
});
// Configure our app to serve static files from the current directory
app.use(express.static('./'));
// Display `index.html` when localhost:3000 is requested
app.get('/', function (req, res) {
res.sendFile('./index.html', {root: './'});
});
// Send all records when there's a GET request to `localhost:3000/test`
app.get('/test', function (req, res) {
db.list({ include_docs: true }, function(err, body){
res.send(body);
});
});