##文件保存

Node.js 里面保存文件比较简单。

// 声明依赖模组
var fs = require('fs'),
	data = "Same data I want to write to a file."
// 写入数据	
fs.writeFile('file1.txt', data, function (err, data){
	if (err) {throw err;};
	console.log("data has been written");
});
// 读取数据
fs.readFile('file1.txt', 'utf8', function (err, data){
	if (err) {throw err;};
	console.log('file 1 read:' + data);
});

##数据库保存 ###关系型数据库

现在普遍使用的还都是关系型数据库。这里以mysql为例:

####连接数据库 var http = require(“http”),
mysql = require(“mysql”); // 声明mysql模块

var connection = mysql.createConnection({  
	user: "root", //数据库用户名  
	password: "", //数据库密码  
	database: "node" //数据库  
});  

http.createServer(function (request, response) {  
	// 连接数据库,并把数据库中所有的记录发送到界面 
	connection.query('select * from user;', function (error, rows, fields) {  
    	response.writeHead(200, { "Content-Type": "text/plain" });  
    	response.end(JSON.stringify(rows));  
	});  
}).listen(8080);  

####mysql的CRUD操作

和别的数据库操作,并无不同。 具体的操作可以查看Github, 这里还有中文译文

###MongoDB MongoDB是Node.js常用的NoSql数据库之一。 我们可以在这里,获取到安装的相关细节。 当然有些小伙伴也需要一个图形界面的数据库客户端,我们在这里使用MongoHub

在使用之前,我们需要把MongoDB加到我们项目中的依赖里。

{
"name": "connect_to_mongo",
"version": "0.0.1",
"private": true,
"scripts": {
	"start": "node ./bin/www"
},
"dependencies": {
	"express": "~4.2.0",
	"static-favicon": "~1.0.0",
	"morgan": "~1.0.0",
	"cookie-parser": "~1.0.1",
	"body-parser": "~1.0.0",
	"debug": "~0.7.4",
	"jade": "~1.3.0",
	"mongoose":">=2.3.1" // 这里加入依赖
	}
}

####连接MongoDB

var mongoose = require('mongoose');
// connect mondodb
mongoose.connect('mongodb://localhost/todo_development',function(err){
	if (!err) {
    	console.log('Connect to MongoDB');
	} else{
   	 throw err;
	};
});