Node.js学习-01基本使用

427 阅读4分钟

Node.js学习-01基本使用

使用Node执行JS脚本

node Hello.js
const foo = 'Hello Node';
console.log(foo);

注意:

  • 文件名不要命名为node.js

  • Node 中获取不到window和document(没有DOM和BOM)

Node读取文件

// 1. 使用require方法加载fs核心模块
var fs = require('fs');

// 2. 读取文件
// 第一个参数就是要读取的文件路径
// 第二个参数是一个回调函数
// 成功: data 数据  error: null
// 失败: data null error: 错误对象
fs.readFile('./file.txt', function(error, data) {   
    console.log(error);
    // <Buffer 74 68 69 73 20 69 73 20 61 20 66 69 6c 65>
    // 二进制数据,转化为16进制了
    console.log(data);
    console.log(data.toString()); // this is a file

    // 简单的错误处理
    if (error) {
        console.log('读取文件失败了');
    } else {
        console.log(data.toString());
    }
})

Node写文件

var fs = require('fs');

fs.writeFile('./write.txt', '大哥大嫂过年好', function(error) {
    if (error) {
        console.log('文件写入失败');
    } else {
        console.log('文件写入成功');
    }
});

简单的http服务

最简单的http服务

// 使用Node构建一个web服务器

// 1. 加载http核心模块
var http = require('http');

// 2. 使用http.createServer()方法创建一个web服务器,返回一个server实例
var server = http.createServer();

// 3. 接收请求,处理请求,发送响应
// 注册request请求事件
// 当客户端请求过来,就会自动触发服务器的request的请求事件,然后执行第二个参数:回调处理函数
server.on('request', function() {
    console.log('收到客户端的请求了');
});

// 4. 绑定端口号,绑定服务器
server.listen(3000, function() {
    console.log('服务器启动成功了,可以通过 http://127.0.0.1:3000/ 来进行访问');
});

发送响应

// 使用Node构建一个web服务器

// 1. 加载http核心模块
var http = require('http');

// 2. 使用http.createServer()方法创建一个web服务器,返回一个server实例
var server = http.createServer();

// 3. 接收请求,处理请求,发送响应
// 注册request请求事件
// 当客户端请求过来,就会自动触发服务器的request的请求事件,然后执行第二个参数:回调处理函数
// 回调函数接收2个参数
// request: 请求对象,请求对象可以用来获取客户端的一些请求信息,例如请求路径
// response: 响应对象,响应对象可以用来给客户端发送响应消息
server.on('request', function(request, response) {
    console.log('收到客户端的请求了,请求路径是: ' + request.url);

    // response具有一个write方法,可以用来给客户端发送响应数据
    // write可以使用多次,但是最后一定要使用end来结束,否则客户端会一直等待
    // response.write('hello');
    // response.write(' nodejs');

    // 告诉客户端,响应结束
    // response.end('Hello World');

    // 根据不同的请求路径,发送不同的响应结果
    // 1. 获取请求路径 2. 判断路径处理响应
    var url = request.url;

    if (url === '/') {
        response.end('index page');
    } else if (url === '/login') {
        response.end('login page');
    } else {
        response.end('404 Not Found');
    }

    // 响应内容只能是字符串,数字,对象,数组,布尔值都不行
    // var obj = {
    //     name: 'xx',
    //     age: 18
    // };
    // response.end(JSON.stringify(obj));
});

// 4. 绑定端口号,绑定服务器
server.listen(3000, function() {
    console.log('服务器启动成功了,可以通过 http://127.0.0.1:3000/ 来进行访问');
});

Node中JS的核心模块

常用的核心模块

  • fs 文件系统
  • http 网络请求
  • OS 操作系统
  • path 路径
  • ...

Node中的模块系统

moduleA.js

// require是一个方法,用于加载模块的
// 在Node中,模块有三种
// 1. 具名的核心模块: fs, http
// 2. 用户自己编写的文件模块:js文件 commonjs
// 3. 第三方模块
console.log('a start');
require('./moduleB.js');
console.log('a end');

/**
 * a start
 * B模块 文件被加载执行了
 * a end
 */

moduleB.js

console.log('B模块 文件被加载执行了');
  • 在Node中,没有全局作用域,只有模块作用域,moduleA和moduleB中相同命名的对象不会冲突
  • 外部不会影响内部,内部也不会影响外部

既然模块默认是封闭的,那如何让模块与模块之间进行通信?

moduleB.js

var foo = 'bbb';
// 将所有需要外部访问的成员绑定到exports上
exports.foo = 'hello'; // 导出的对象

moduleA.js

var bExports = require('./moduleB.js');
console.log(bExports.foo); // 'hello'

IP地址和端口

IP识别互联网中的计算机,端口识别计算机上的应用程序

响应内容类型Content-type

  • 服务端默认发送的数据,UTF8编码
  • 但是,浏览器在不知道浏览器响应内容编码的情况下,会按照当前操作系统的默认编码去解析
  • 中文操作系统默认是GBK
  • 解决办法:正确告诉浏览器发送内容的编码
response.setHeader('Content-Type', 'text/plain; charset=utf-8'); // 解决中文乱码

content-type: 告知发送的数据类型是什么类型

  • text/plain 普通文本
  • text/html html
  • text/css css
  • imgae/jpep jpeg

发送文件中的数据以及Content-type内容类型

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

var server = http.createServer();

server.on('request', function(req, res) {
    var url = req.url;

    if (url === '/') {
        fs.readFile('./resource/index.html', function(err, data) {
            if (err) {
                res.setHeader('Content-type', 'text/plain; charset=utf-8');
                res.end('文件读取失败,请稍后重试!');
            } else {
                res.setHeader('Content-type', 'text/html; charset=utf-8');
                res.end(data);
            }
        })
    } else if (url === '/ab2') {
        fs.readFile('./resource/ab2.png', function(err, data) {
            if (err) {
                res.setHeader('Content-type', 'text/plain; charset=utf-8');
                res.end('文件读取失败,请稍后重试!');
            } else {
                res.setHeader('Content-type', 'imgae/jpep;');
                res.end(data);
            }
        })
    } 
})

server.listen(3000, function() {
    console.log('服务器启动成功了,可以通过 http://127.0.0.1:3000/ 来进行访问');
})