吃饭用的前端

Node

2019-05-25  本文已影响0人  CNLISIYIII

Node中文网:http://Nodejs.cn/


(一)全局变量global

global中的成员

console.log(123);
if (5 > 4) {
    console.log('大于');
}
global.console.log(1234);
global.setTimeout(() => {
    console.log('suibian');
}, 2000);
console.log(__dirname);
console.log(__filename);
//输出结果
//123
//大于
//1234
///Users/lisiyi/AJAX/code/public
///Users/lisiyi/AJAX/code/public/demo.js
//suibian

(二)Node核心模块

要使用一个模块的话必须先加载(引入)该模块。

1.path模块(处理路径模块)

使用方法:

// 使用核心模块之前,首先加载核心模块
let path = require('path');
// 或者
const path = require('path');

path模块中的方法:


代码举栗:
const path = require('path');

// extname -- 获取文件后缀
console.log(path.extname('index.html')); // .html
console.log(path.extname('index.coffee.md')); // .md

// join -- 智能拼接路径
console.log(path.join('/a', 'b', 'c')); // \a\b\c
console.log(path.join('a', 'b', 'c')); // a\b\c
console.log(path.join('/a', '/b/../c')); // \a\c
console.log(path.join('/a', 'b', 'index.html')); // \a\b\index.html
console.log(path.join(__dirname, 'a', 'index.html')); // 得到一个绝对路径

2.fs模块(文件操作模块)

引入模块的时候,可以使用var、let,但是建议使用const,因为我们不希望它改变。

//加载模块,得到一个对象。
const fs = require('fs');
console.log(fs);

readFile异步读取文件。其中[编码]可选,默认输出buffer类型的数据。

const fs = require('fs');
// fs.readFile(文件路径, [编码], 回调函数处理读取的内容);
fs.readFile('index.html', 'utf-8', (err, data) => {
    //err表示是否有错误,有错误的话err表示错误信息,是一个字符串。没有错误err是undefined
    if (err) {
        console.log(err); //若有错误,输出错误
        return; //阻止后续代码
    }
    console.log(data); //输出读取的内容
});

writeFile异步写入文件。会将文件中原有的内容覆盖掉。若写入文件不存在,则会自动创建文件。

const fs = require('fs');
// 调用writeFile方法,写入文件
// fs.writeFile(文件路径,写入的内容,回调函数查看是否有错误);
fs.writeFile('demo.txt', 'how are you', (err) => {
    if (err) {
        console.log(err);
    }
    else {
        console.log('success');
    }
})

3.querystring模块(查询字符串处理模块)

//加载模块
const querystring = require('querystring');
// parse方法是将查询字符串转换成JS对象,是querystring对象中封装的,不是JSON.parse。
let result = querystring.parse('id=123&name=zs&age=20');
console.log(result); // { id: '123', name: 'zs', age: '20' }
console.log(querystring.stringify(result)); //id=123&name=zs&age=20

4.url模块

旧的API使用:

const url = require('url');
//let res = url.parse('http://www.baidu.com:80/test.html?id=123&age=20');
let res = url.parse('test.html?id=123&age=20'); //url不完整也可以解析
console.log(res); //解析出一个对象
//获取参数
console.log(res.query); //id=123&age=20
//引入querystring处理res.query
const querystring = require('querystring');
console.log(querystring.parse(res.query)); //{ id: '123', age: '20' }

新的API使用:实例化URL的时候,必须传递一个完整的url,否则会报错

const myUrl = new URL('http://www.baidu.com/test.html?id=123&age=20');
// const myUrl = new URL('test.html?id=123&age=20'); //报错,无效的url
//传两个参数组成完整的url,不会报错
// const myUrl = new URL('test.html?id=123&age=20', 'http://www.xyz.com'); 
console.log(myUrl); //解析出一个对象,包含了url的各个组成部分
//比旧的API多了searchParams
console.log(myUrl.searchParams); //URLSearchParams { 'id' => '123', 'age' => '20' }
//获取id参数
console.log(myUrl.searchParams.id); //undefined
console.log(myUrl.searchParams.get('id')); //必须调用searchParams对象中的get方法来获取

(三)http模块(服务器处理模块)

node不同于Apache,安装完node并没有一个能够提供Web服务环境,需要使用http模块自己来搭建Web服务器。

1.使用http模块搭建Web服务器

//加载http模块
const http = require('http');
//调用http模块中的createServer方法,创建服务器
const server = http.createServer();
//启动服务器,并且要为服务器设置端口
server.listen(3000, () => {
    console.log('服务器启动了');
});
//添加request事件,用于处理所有的http请求
server.on('request', () => {
    console.log('你的请求我收到了');
});

2.如何对浏览器的请求作出响应

const http = require('http');
const server = http.createServer();
server.listen(3000, () => {
    console.log('服务器启动了');
});
server.on('request', (req, res) => {
    //事件处理函数有两个参数
    //req表示request,所有和请求相关的信息都可以通过request对象来接收
    //res表示response,所有和响应相关的都可以使用response对象来处理
    console.log('你的请求我收到了');
    //通过res.setHeader()方法来设置响应头,若不设置会出现中文乱码
    res.setHeader('Content-Type','text/html; charset=utf-8');
    //通过res对象的end方法来对浏览器作出响应
    //res.end()方法的作用是将响应报文(行、头、体)返回给浏览器
    res.end('你的请求我收到了');
});

3.根据不同url处理不同请求

const http = require('http');
const server = http.createServer();
server.listen(8000, () => console.log('start'));
server.on('request', (req, res) => {
    /*
    req.url 表示请求的url,形如/index.html
    req.method 表示请求方式,比如GET
    req.headers 表示所有的请求头,是一个对象
    */
    let url = req.url;
    //判断,根据url返回信息
    if (url === 'index.html') {
        //读取index.html并返回内容
        res.setHeader('content-type', 'text/html;charset=utf-8');
        res.end('你请求的是index.html');
    }
    else if (url === '/getMsg') {
        //读取数据并返回
        res.setHeader('content-type', 'text/html;charset=utf-8');
        res.end('你请求的是getMsg接口')
    }
    else {
        //服务器没有浏览器请求的文件或接口
        res.setHeader('content-type', 'text/html;charset=utf-8');
        res.statusCode = 404; //不存在,设置状态码为404
        res.end('你请求的文件不存在')
    }
})

4.处理浏览器POST方式提交的数据

const http = require('http');
const server = http.createServer();
server.listen(8000, () => console.log('start'));
server.on('request', (req, res) => {
    //判断是否是POST方式请求
    if (req.method === 'POST' && req.url === '/addMsg') {
        console.log(1234);
        //服务器端接收数据的时候是分块接收的
        //需要data事件,将浏览器发送过来的数据拼接到一起
        let str = '';
        req.on('data', (chunk) => {
            str += chunk;
        });
        //如果已经将全部数据接收到了,则触发end事件,在这个事件中可以获取到所有数据
        req.on('end', () => {
            console.log(str); 
        });
    }
})

使用postman测试:



终端输出结果:

1234
name=lisiyi&content=imlisiyi

5.处理外部静态资源

为不同的文件类型设置不同的 Content-Type

response.setHeader('Content-Type', 'text/css');
上一篇 下一篇

猜你喜欢

热点阅读