Node.js学习笔记Day1

Day1

Node.js是什么

1.Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.

node.js是一个js运行环境
node.js可以解释和执行js代码
浏览器中的JavaScript分为3部分:

1)EcmaScript(基本的语法,如if、var、function等)

2)BOM

3)DOM

node.js中的JavaScript:

1)EcmaScript<>
2)为JavaScript提供了一些服务器级别的操作API(文件读写、网络通信、http服务器等)

2.Node.js uses an event-driven,non-blocking I/O model that makes it lightweight and efficient

关键字:事件驱动,NIO,轻量高效

3.Node.js's package ecosystem,npm,is the largest ecosystem of open source libraries in the world

拥有包的生态系统,npm,类似于java后台中使用的maven

Node.js能做什么

  1. Web服务器后台
  2. 命令行工具

Node.js读写文件的操作

var fs = require('fs');
fs.readFile('文件路径',function(error,data){
//error是错误对象,data是读取到的文件的内容
});
fs.writeFile('要写文件到哪个路径','要写的内容',function(error){
//error是错误对象
});

node.js简单的http服务
var http = require('http');
var server = http.createServer();
server.on('request',funciton(request,response){

});
serve.listen(端口号,function(){
//绑定端口号之后的回调
})

引用自定义的js文件模块

现有a.js文件与b.js文件在同一目录下,需要在a中引用b,则在a中写:

var b = require(‘./b.js’);

注意一定要带上路径定位符号./ 不然会会将b.js识别成系统模块而报错;末尾的.js可以省略

需要在a中使用b中的数据,需要将b中的数据使用一个名为exports的参数进行挂载:

在b中:exports.param='hello';

在a中:使用var b = require(‘./b.js’);引入b.js
使用b.param则可以得到hello

同理还可以在b中挂载方法到exports上:

exports.add = function(a,b){ return a+b; }

获取请求方的IP地址和端口号

  1. 引入http模块,在server.on的回调中使用request参数获取请求方的IP地址和端口号
  2. console.log("请求方的地址是:"+req.socket.remoteAddress+"端口号是:"+req.socket.remotePort);

Content-Type

为了解决响应中文乱码的问题,课程中简单介绍了一下content-type

输出之前设置字符集编码utf-8

res.setHeader('Content-type','text/plain;charset=utf-8');

关于content-type的详细类型可参考http://www.runoob.com/http/http-content-type.html


示例:使用'text/plain'的类型,res.end('

hello node

'),会在页面上输出

hello node


使用'text/html'的类型,res.end('

hello node

')
,会在页面上输出hello node
(不设置content-type时,浏览器按照text/html对输出进行解析

你可能感兴趣的:(Node.js学习笔记Day1)