日期:2014-05-16  浏览次数:20368 次

服务端的javascript脚本node.js示例代码

Node.js是一套用来编写高性能网络服务器的JavaScript工具包,一系列的变化由此开始。比较独特的是,Node.js会假设你是在POSIX环境下运行它Linux 或 Mac OS X。如果你是在Windows下,那就需要安装MinGW以获得一个仿POSIX的环境。在Node中,Http是首要的。Node为创建http服务器作了优化,所以你在网上看到的大部分示例和库都是集中在web上(http框架、模板库等)

软件首页:http://nodejs.org

读取文件到字符串

?

var fs = require('fs');

var file = fs.readFileSync(path, "utf8");

console.log(file);

?

编写的一个简单的 HTTP 服务器

?

var sys = require(sys),
http = require(http);
server = http.createServer(function (req, res) {
? res.writeHeader(200, {Content-Type: text/plain});
? res.write(Hello World);
? res.close();
})
server.listen(8000);
sys.puts(Server running at a href="http://127.0.0.1:8000/);

?

读取mongoDB并输出json数据

运行此源码必须
1、安装node mongodb native驱动
2、express js框架(不安装的话简单修改index.js即可)
3、安装了mongoDB,并且有comments数据库comments collection。collection里有数据。
如果名字不一样,进index.js就可以修改。端口必须是默认的。
3、node index.js,打开127.0.0.1:8001就可以看到返回了数据

?index.js

var express = require('express');

var app = express.createServer();

var db = require('./tea/db');

db.open({dbName:'comments'});

app.get('/',function(req,res){

db.findOne('comments',{},function(records){

res.send(records);

});

});

app.listen(8001);

/tea/index.js

var tea = exports;

tea.hello = function(){

console.log('hello world');

}

/tea/db.js

var mongo = require('mongodb');

var tea = tea || {};

tea.db = exports;

tea.db.server = '127.0.0.1';

tea.db.port = 27017;