node入门
来源:互联网 发布:网络架构工程师干什么 编辑:程序博客网 时间:2024/06/09 19:04
开启一个HTTP服务向前台打印hello
var http = require('http'); //创建http对象http.createServer(function(request,response){ //用http对象创建一个web服务,传两个参数一个请求对象一个响应对象 response.writeHead(200,{'ContentType':'text/html;charset=utf-8'})//输出类型和编码格式 response.write('hello world ');//向网页中输出hello world response.end('end'); //请求结束}).listen(8887);
调用模块(对象)
- 再node中仍然可以使用js中面向对象编程的方法。
- 可以使用CommonJS的方法对文件的函数导入和导出。
认识路由
- 后台通过前台把地址栏传过来的url进行解析,获取有用的字符串信息,
并把路由信息打印到后台
var http = require('http'); //创建http对象var url = require('url'); //创建url对象http.createServer(function(request,response){ //用http对象创建一个web服务,传两个参数一个请求对象一个响应对象 response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})//输出类型和编码格式 var pathname = url.parse(request.url).pathname;//从地址栏中的字符串中截取需要的路径文件。request.url便是地址栏中的完整url字符串。 pathname = pathname.replace(/\//,'');//去掉前面的斜杠 console.log(pathname);//得到路径文件名,以便下一步使用 response.end('end0'); //请求结束}).listen(8887);
文件的读取
- 同步读取
//以同步的方式从当前目录读取xx.html文件并打印出来 var http = require('http'); //创建http对象 var url = require('url'); var fs = require('fs'); //引入文件模块 console.log('http服务启动成功');http.createServer(function(request,response){ //用http对象创建一个web服务,传两个参数一个请求对象一个响应对象 response.writeHead(200,{'ContentType':'text/html;charset=utf-8'})//输出类型和编码格式 var data = fs.readFileSync('./xx.html','utf-8'); console.log(data); response.write(data); response.end('end'); //请求结束sole.log('1111');}).listen(8888);
- 异步读取
//读取当前目录下的a.txt数据并打印出来 var http = require('http'); //创建http对象 var url = require('url'); var fs = require('fs'); //引入文件模块 console.log('http服务启动成功');http.createServer(function(request,response){ //用http对象创建一个web服务,传两个参数一个请求对象一个响应对象 response.writeHead(200,{'ContentType':'text/html;charset=utf-8'})//输出类型和编码格式 fs.readFile('a.txt',function(err,data){ if(err){ console.log(err); } else{ console.log(data.toString()); } }); response.end('end'); //请求结束sole.log('1111');}).listen(8888);
文件的写入
与文件的读取一样,也分为同步写入和异步写入,同步写入的时候下一个程序只有等上一步文件写入操作完成时才会开始执行,而异步操作时下一个程序无需等待,上一步的文件写入和下一个程序的执行是分开的异步的。
异步写入文件举例:
-创建一个b.txt文件,并把data字符串中的数据保存在文件中 var http = require('http'); //创建http对象 var url = require('url'); var fs = require('fs'); //引入文件模块 console.log('http服务启动成功');http.createServer(function(request,response){ //用http对象创建一个web服务,传两个参数一个请求对象一个响应对象 response.writeHead(200,{'ContentType':'text/html;charset=utf-8'})//输出类型和编码格式 var data = '我是要异步写入的数据'; fs.writeFile('b.txt',data,function(err){ //异步写入 if(err){ throw err; } else{ console.log('写文件成功'); } }); response.end('end');}).listen(8888);
阅读全文
0 0
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- Node入门
- node入门
- node入门
- qduoj 65 again and again 字典树
- Memcached基本操作
- B
- HDU 3988-Harry Potter and the Hide Story(分解素数)
- Python 用BeautifulSoup 解析Html
- node入门
- CodeForces
- CSU 1974:神奇药水(水?)
- Linux编程学习之进程间通信篇-进程间通信概述
- c#使用wpd读取便携式设备信息二
- 阿里巴巴2016前端工程师笔试题1总结
- C语言关键字 union基本知识
- TensorFlow(二)实现Softmax Regression 识别手写数字
- 506