nodejs 写文件

版权声明:版权有就有吧。 https://blog.csdn.net/m0_38044453/article/details/83584769
var http = require('http');

var url = require('url');

var router = require('./router');

http.createServer(function(request,response){
	response.writeHead(200,{'Contet_Type':'text/html;charset=utf-8'});

	if(request.url!=='/favicon.ico'){
		var pathname = url.parse(request.url).pathname;
		pathname = pathname.replace(/\//,'');
		
		router[pathname](request,response);

	}

}).listen(8000);

console.log('now Server is 8000');
var file = require('./file');

module.exports = {
	writeFile:function(req,res){

		function recall(data){
			res.write('异步写文件成功');
			res.end('');// 不写则没有http协议尾
		}

		file.writefile('./file/异步.txt','这是异步写文件',recall);
	},
	writeFileSync:function(req,res){

		res.write('同步写文件成功');
		res.end('');
		file.writeFileSync('./file/同步.txt','这是同步写文件');
	
	}

}
var fs = require('fs');
module.exports={
	writefile:function(path,data,recall){
		fs.writeFile(path,data,function(err){
			if(err){
				throw err;
			}
			console.log('It\' saved!,异步写文件完成');
			recall('异步写文件成功')
		});
	},
	writeFileSync:function(path,data){
		fs.writeFileSync(path,data);
		console.log('同步写文件完成');
	} 

}

猜你喜欢

转载自blog.csdn.net/m0_38044453/article/details/83584769