NodejsとMongoDB初体験
4444 ワード
NodejsとMongoDBを勉強して、サンプルプログラムを書いて、データベースの中の製品のリストを読みました。
01
02
03
04
05
06
07
08
09
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
50
51
52
53
54
55
56
01
02
03
04
05
06
07
08
09
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
50
51
52
53
54
55
56
var
http = require(
"http"
),
mongo = require(
"mongodb"
),
events = require(
"events"
);
http.createServer(
function
(req, res) {
var
products_emitter =
new
events.EventEmitter(),
// northwind 。 use northwind
db =
new
mongo.Db(
"northwind"
,
new
mongo.Server(
'localhost'
, 27017, {}), {});
var
listener =
function
(products) {
var
html = [], len = products.length;
html.push(
'<!DOCTYPE html>'
);
html.push(
'<html>'
);
html.push(
'<head>'
);
html.push(
'<title>Nodejs</title>'
);
html.push(
'</head>'
);
html.push(
'<body>'
);
if
(len > 0) {
html.push(
'<ul>'
);
for
(
var
i = 0; i < len; i++) {
html.push(
'<li>'
+ products[i].name +
'</li>'
);
}
html.push(
'</ul>'
);
}
html.push(
'</body>'
);
html.push(
'</html>'
);
res.writeHead(200,
"Content-Type: text/html"
);
res.write(html.join(
''
));
res.end();
clearTimeout(timeout);
}
products_emitter.on(
'products'
, listener);
var
timeout = setTimeout(
function
() {
products_emitter.emit(
'products'
, []);
products_emitter.removeListener(
'products'
, listener);
}, 10000);
db.open(
function
() {
// products
db.collection(
"products"
,
function
(err, collection) {
// select * from products db.products.find()
collection.find(
function
(err, cursor) {
cursor.toArray(
function
(err, items) {
products_emitter.emit(
'products'
, items);
});
});
});
});
}).listen(8000);
console.log(
"Started"
);