01nodejs入门


1.初体验(REPL)

  1. R(read) 读取(读取用户输入的代码)
  2. E(exec) 执行 (执行用户输入的代码)
  3. P(print) 打印(打印用户输入的js代码)
  4. L(loop) 循环 (后续所有js代码执行都会循环以上命令)
  5. 退出:ctrl+c

    1.1通过命令行运行js代码

  6. 命令行输入node启动node后直接输入js代码
  7. 命令行node xx.js运行js文件
    (cls清屏)

    2.模块系统

    js三大组成部分:
  8. ecmascript(声明js变量,判断,循环等语法)
  9. dom(document)
  10. BOM(window,local等)
    模块(http服务器等)

    2.1简介

    2.1.1使用Nodejs编写应用程序主要使用

  • ecmascript语法:变量、判断、循环等(js三大组成部分:ECMA/DOM/BOM)
  • 内置核心模块:http服务、fs文件操作、url路径、path路径处理、os操作系统
  • 第三方模块:
  • 自定义模块:自己创建的js文件

    2.2.2CommonJS模块模范

  • 一个文件就是一个模块
  • 通过require来加载模块
  • 通过exports和modul.exports来到导出模块中的成员(声明模块中哪些功能可以使用)

    2.2自定义Node.js模块

    2.2.1语法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    步骤1:导出成员(声明模块中/文件中哪些方法可以被外部使用)
    //写法1
    exports.属性/方法名=功能
    //写法2
    module.exports.属性/方法名=变量名
    步骤2:外部引入使用
    //使用:先引入再调用
    var 对象=require('路径及文件名')
    对象.属性或方法名

image-20210801202634827

2.3第三方模块

2.4Node.js内置模块

内置模块
api手册

2.4.1获取操作系统信息(os模块) –了解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 字节是计算机中的一种计量单位,表示数据量的多少 
// 1字节(Byte)= 8位(bit)
// 1KB = 1024Byte(字节)
// 1MB = 1024KB
// 1GB = 1024MB
// 1TB = 1024GB

//1.创建os对象(引入nodejs内置os模块)
var os = require("os");
//2.调用os对象方法获取系统数据
console.log('hello,另起一行' + os.EOL + 'itcast');
console.log('主机名: ' + os.hostname());
console.log('操作系统名: ' + os.type());
console.log('操作系统平台: ' + os.platform());
console.log('内存总量: ' + os.totalmem() + " 字节.");
console.log('空闲内存: ' + os.freemem() + " 字节.");

2.4.2路径处理(path模块)

1
2
3
4
5
6
7
8
9
10
11
//dirname  去最后一个
//basename 取最后一个

//1.创建path对象(引入nodejs内置path模块)
var path = require("path");
//2.调用path对象方法
var testData = 'c:/app/view/godos/add.html';
console.log(path.extname(testData)); //取后缀(包括.)
console.log(path.basename(testData));//取最后一层
console.log(path.dirname(testData)); //去最后一层
console.log(path.dirname(path.dirname(testData)));

2.4.3网址处理(url模块)

1
2
3
4
5
6
7
8
9
10
11
//1.创建url对象(引入nodejs内置url模块)
var url = require("url");
//2.调用url对象方法
var wangzhi = "http://itcast.cn?name=张三&age=18";
console.log(url.parse(wangzhi)); //解析网址
console.log(url.parse(wangzhi, true)); //解析网址参数为对象

var param = url.parse(wangzhi, true).query;
console.log(param);
console.log(param.name);
console.log(param.age);

2.4.4文件处理(fs模块)

2.4.4.1写入文件

语法:

1
2
3
4
5
6
7
8
//1.创建fs对象(引入node内置的fs模块)
var fs = require('fs');

//2.调用函数写数据进文件
fs.writeFile(路径及文件名,数据,function(err){
err 为null - 则写入成功
err不为null - 则写入失败
});

练习:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//1.创建fs对象(引入node内置的fs模块)
var fs = require('fs');

//2.调用函数写数据进文件
fs.writeFile('./a.txt', '你好,hybs', function(err) {
// err 为null - 则写入成功
// err不为null - 则写入失败
if (err) {
console.log(err);
return;
}

console.log('写入成功');
});

2.4.4.2读取文件
1
2
3
4
5
6
7
8
9
10
11
fs.readFile('../../data/data01.txt', 'utf-8', function(err,data) {    //不加解码类型会是buffer对象
// err 为null - 则写入成功
// err不为null - 则写入失败
if (err) {
console.log(err);
return;
}
console.log(data)
console.log('读取成功');
console.log(data.toString()) //通过buffer.tostring()转化为string类型
});

2.4.5引入http服务器并创建服务器

  1. 创建http服务器
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    //说明
    //nodejs作用:1-提供JS运行环境,2-提供N多模块(API)让JS更强大

    //1.创建http对象(引入node内置的http模块)
    var http = require('http');

    //2.创建http服务器(调用http对象的createServer)
    var server = http.createServer();

    //3.监听用户请求
    server.on('request', function() {
    console.log('收到客户端请求了');
    });

    //4.启动服务器
    server.listen(8080, function(){
    console.log('服务已启动,可以通过:http://localhost:8080 访问测试')
    });
  2. 响应数据
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    //1.创建http对象(引入node内置的http模块)
    var http = require('http');

    //2.创建http服务器(调用http对象的createServer)
    var server = http.createServer();

    //3.监听用户请求(形参:request-请求对象,response-响应对象)
    server.on('request', function(request, response) {
    //有请求DOS窗口就输出
    console.log('收到客户端请求了,请求路径是:' + request.url);
    //响应请求
    //write方法:声明给客户端发送的数据
    //end方法: 结束响应
    response.write('hello,');
    response.write('itcast');
    response.end();
    });

    //4.启动服务器
    server.listen(8080, function(){
    console.log('服务已启动,可以通过:http://localhost:8080 访问测试')
    });
  3. 响应不同数据
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    //1.创建http对象(引入node内置的http模块)
    var http = require('http');

    //2.创建http服务器(调用http对象的createServer)
    var server = http.createServer();

    //3.监听用户请求(形参:request-请求对象,response-响应对象)
    server.on('request', function(request, response) {

    //获取请求路径(注:默认请求站点根目录)
    var url = request.url;
    //判断请求路径
    if (url == '/') {
    var content = 'this is index';
    } else if (url == '/login') {
    var content = 'this is login';
    } else {
    var content = '404 Not Found';
    }
    //响应请求
    response.write(content);
    response.end();
    });

    //4.启动服务器
    server.listen(8080, function(){
    console.log('服务已启动,可以通过:http://localhost:8080 访问测试')
    });
  4. 解决中文乱码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    //说明
    //nodejs作用:1-提供JS运行环境,2-提供N多模块(API)让JS更强大

    //1.创建http对象(引入node内置的http模块)
    var http = require('http');

    //2.创建http服务器(调用http对象的createServer)
    var server = http.createServer();

    //3.监听用户请求(形参:request-请求对象,response-响应对象)
    server.on('request', function(request, response) {

    //响应请求
    response.setHeader('Content-Type', 'text/html; charset=utf-8');
    response.write("哥哥来抓我呀,<a href='http://nn.com'>点击进入我的世界</a>");
    response.end();

    });

    //4.启动服务器
    server.listen(8080, function(){
    console.log('服务已启动,可以通过:http://localhost:8080 访问测试')
    });

    2.4.6请求和响应对象

  5. 请求对象
    1
    2
    3
    4
    5
    req.headers     	获取请求头信息(对象)
    req.rawHeaders 获取请求头信息(数组)
    req.httpVersion 获取HTTP版本
    req.method 获取请求方法
    req.url 获取请求路径(注:不含网址)
  6. 响应对象
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    res.statusCode = 404;
    res.statusMessage = 'Not Found';
    res.setHeader('Content-Type', 'text/html; charset=utf-8')

    //简化版
    res.writeHeader(404, 'Not Found', {
    'Content-Type' : 'text/html; charset=utf8'
    })

    res.write(数据)
    res.end()
    (响应应查看mime类型)

    es6新特性

  7. es6标签替换
    1
    2
    3
    4
    5
    6
    var html1=``;
    msgs.forEach(function (items) {
    html1+=`<li class="list-group-item">${items.name}:${items.content} <span class="pull-right">${items.create_at}</span></li>`

    })
    lg.innerHTML=html1
  8. 传统标签替换
    1
    2
    3
    4
    5
    6
    7
    8
     var eleLi="";
    for (var i=0;i<msgs.length;i++){

    eleLi+="<li class='list-group-item'>"+msgs[i].name+'说:'+msgs[i].content+" <span class='pull-right'>"+msgs[i].create_at+"</span></li>"


    }
    lg.innerHTML=eleLi

切换NodeJS版本

img

img

img

img

img

img

img

img

img

img

  • 通过nvm查看托管nodejs版本 -> 安装测试版 -> 切换测试版 -> 验证

img

img

img

  • 切换稳定版 -> 验证

img

解决nvm下载慢的问题

  1. 命令行输入 where nvm

  2. 在提示目录下找到settings.txt

  3. 后面添加淘宝镜像:

    1
    2
    node_mirror: https://npm.taobao.org/mirrors/node/
    npm_mirror: https://npm.taobao.org/mirrors/npm/

文章作者: 哈雅布撒
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 哈雅布撒 !
  目录