node.js入门指南

一,node.js选择

(1)在整个开源社区,node.js是当之无愧的、最流行的开发平台之一;

(2)在钱包、交易市场等客户端应用领域,node.js的应用较为广泛;

(3)在加密货币核心代码的开发上,node.js的应用较少

二,通俗地解释是,node.js是一个可以让你利用 javascript语言 开发应用 的平台,是构建运行在分布式设备上的数据密集型实时程序(比如聊天室、即时通信等等)的完美选择。

三,安装node.js,终端运行,

(1)切换盘符,针对window,比如 e:

(2)改变目录,cd 目录名

(3)执行程序,node ###.js(文件名)

四,http来写一个真正的服务器

引入--创建--监听

http.createServer(function(req,res){
	switch(req.url){
		case '/1.html':
			res.write('1111');
			break;
		case '/2.html':
			res.write('2222');
			break;	
		default:
			res.write('404');
	}
	res.end();
})

按照浏览器请求的不同,响应不同的内容;

五,文件操作fs

fs.readFile('文件名',function(err,data){})

fs.readFile('aa.text', function(err,data){
	if(err){
		console.log('读取失败');
	}else{
		console.log(data.toString());
	}
});

fs.writeFile('文件名','内容',function(err){})

fs.writeFile('bb.text', '123wewfcdscvdfbgthjynuy', function(err){
	console.log(err);
});

六,http和fs结合===真正的服务器(不需要再重启服务器,因为他不是再服务器里面写的,实在文件里写的)

const http = require('http');
const fs = require('fs');

var server = http.createServer(function(req,res){
	//req.url => '/index.html'
	//读取 =>'./www/index.html'
	//'./www'+req.url
	
	fs.readFile('./www'+req.url,function(err,data){
		//console.log(err)
		if(err){
			res.write('404')
		}else{
			res.write(data)//响应到前台
		}

		res.end();//文件读取结束之后关闭响应
	});
});

server.listen(8090);


猜你喜欢

转载自blog.csdn.net/qq_33828155/article/details/80902490