Nodejs 写文件

optfile.js

//-------------optfile.js-------------------------
var fs = require('fs');
module.exports = {
	writefile: function (path, data, recall) { //异步方式
		fs.writeFile(path, data, function (err) {
			if (err) {
				throw err;
			}
			console.log('It\'s  saved!'); //文件被保存
			recall("写文件成功");
		});
	},
	writeFileSync: function (path, data) { //同步方式
		fs.writeFileSync(path, data);
		console.log("同步写文件完成");
	},
}

router.js

var optfile = require('../model/optfile2.js');
module.exports = {
	write: function (req, res) {
		function recall(data) {//闭包函数、回调函数
			console.log(data.toString());
			res.write(data);
			res.end(""); //不写则没有htpp协议尾
		}
		optfile.writefile('./view/02.txt', "+++++我的写文件+++++", recall);
	}
}
//---------写文件-----------
var http = require('http');
var url = require('url');
var router = require('./model/router');
http.createServer(function(request, response) {
	response.writeHead(200, {
		'Content-Type': 'text/html;    charset=utf-8'
	});
	if(request.url !== "/favicon.ico") {
		var pathname = url.parse(request.url).pathname;
		pathname = pathname.replace(/\//, ''); //替换掉前面的/
		if(pathname){
			router[pathname](request, response);
		}else{
			response.end("ok");
		}
		
	}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值