Node.js基础

6/8/2020 Node.js

简单的说 Node.js 就是运行在服务端的 JavaScript。

Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台。

Node.js是一个事件驱动I/O服务端JavaScript环境,基于Google的V8引擎,V8引擎执行Javascript的速度非常快,性能非常好。

# 环境安装

这个不多说了,打开官网 (opens new window)就知道了

安装完之后可以查看一下是否成功

# 查看node版本
node -v
# 查看npm版本
npm -v
1
2
3
4

# node & npm

在安装完环境之后,先初步了解一下nodenpm

一般来说node用来进入node的JavaScript环境(REPL),可以在终端中测试JavaScript,或者直接node index.js去执行一段js.

npm则是个包管理器,简单地说,你可以用它下载安装一些别人发布的包.你还可以去启动一个项目.

一般来说npm的仓库源是国外的,所以一般来说我们会替换源来改善下载的速度,这里安利一下nrm,它可以轻易的切换仓库使用的源

# 安装
npm install -g nrm
# 使用说明
# 查看源可选项
nrm ls
# 大概会出现一下这些
* npm -----  https://registry.npmjs.org/
  yarn ----- https://registry.yarnpkg.com
  cnpm ----  http://r.cnpmjs.org/
  taobao --  https://registry.npm.taobao.org/
  nj ------  https://registry.nodejitsu.com/
  skimdb -- https://skimdb.npmjs.com/registry
# 切换到taobao源
nrm use taobao
# 提示以下则说明成功
Registry has been set to: https://registry.npm.taobao.org/
# 换回原来的源
nrm use npm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# REPL

(Read Eval Print Loop:交互式解释器)

也就是上面说的node指令进入的JavaScript环境

它可以执行以下任务:

  • 读取 - 读取用户输入,解析输入了Javascript 数据结构并存储在内存中。
  • 执行 - 执行输入的数据结构
  • 打印 - 输出结果
  • 循环 - 循环操作以上步骤直到用户两次按下 ctrl-c 按钮退出。

Example

$ node
> let a = 1
undefined
> console.log(a)
1
1
2
3
4
5
# REPL 命令
  • ctrl + c - 退出当前终端。
  • ctrl + c 按下两次 - 退出 Node REPL。
  • ctrl + d - 退出 Node REPL.
  • 向上/向下 键 - 查看输入的历史命令
  • tab - 列出当前命令
  • .help - 列出使用命令
  • .break - 退出多行表达式
  • .clear - 退出多行表达式
  • .save filename - 保存当前的 Node REPL 会话到指定文件
  • .load filename - 载入当前 Node REPL 会话的文件内容。

# 模块系统

require常用来导入当前工程下node_modules中的模块

// 导入读取文件模块
var fs = require("fs");
var data = fs.readFileSync('input.txt');
1
2
3

# 最后

不用好奇为啥没有了,因为很多东西的内容都可以单独写一篇博客了,深入看的话,官方文档绝对是不二选择(推荐有基础的情况下看)

现在你可以去了解api和各种模块了,感兴趣的话还可以了解一下express/koa.值得一提的是,如果你是前端开发者,想实现一些功能简单的后端的话,node.js绝对满足你的要求.


贴一下当时用express写的demo,当时不会es6,写了很多回调地狱 T_T

//express_demo.js 文件
var url = require('url');
var ejs = require('ejs');
var querystring = require('querystring');
const express = require('express');
const fs = require('fs');
const util = require('util');
var mysql = require('mysql');

const app = express();

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'pwd',
    database: 'databaseName'
});
connection.connect();

// 静态文件配置 多个需重复添加
// app.use(express.static('css'));

// render引擎
app.set('views', 'views');
app.set('view engine', 'html');
app.engine('html', ejs.renderFile)
// index
app.get(['/', '/index'], function (req, res) {
    res.sendFile(__dirname+'/views/index.html');
})
// 跳转page
app.get('/page/:pageId', function (req, res) {
    const page = 'page' + req.params.pageId;
    const file = 'views/'+page+'.html';
    fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
        if (err) {
            res.render('pnf');
        }else{
            res.render(page);
        }
    });
})
app.use(function (req, res, next) {
    res.status(404).send("404 Not Found")
})
// 获取所有用户列表
app.get('/getalluser', function (req, res) {
    connection.query('select * from user', function (error, results) {
        if (error) throw error;
        res.send(util.inspect(results, true));
    });
})
// 查询指定客户信息
app.get('/getuser', function (req, res) {
    const params = url.parse(req.url, true).query;
    const addSql = 'select * from user where id = ?';
    const addSqlParams = [params.id];
    connection.query(addSql, addSqlParams, function (error, result) {
        if (error) throw error;
        res.send(util.inspect(result, true));
    });
})
// 新增用户
app.post('/adduser', function (req, res) {
    // 定义了一个post变量,用于暂存请求体的信息
    let body = '';
    // 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
    req.on('data', function (chunk) {
        body += chunk;
    });
    // 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
    req.on('end', function () {
        body = querystring.parse(body);
        const addSql = 'insert into user(`name`,head_image,phone,pwd,email,create_time) values(?,?,?,?,?,now())';
        const addSqlParams = [body.name, body.headImage, body.phone, body.pwd, body.email];
        connection.query(addSql, addSqlParams, function (err, result) {
            if (err) {
                return result;
            }
            res.send('insert success');
        });
    });
})
// 修改用户
app.put('/updateuser', function (req, res) {
    // 定义了一个post变量,用于暂存请求体的信息
    let body = '';
    // 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
    req.on('data', function (chunk) {
        body += chunk;
    });
    // 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
    req.on('end', function () {
        body = querystring.parse(body);
        if (!body.id) {
            res.send('参数错误');
            return;
        }
        const addSql = 'select * from user where id = ?';
        const addSqlParams = [body.id];
        connection.query(addSql, addSqlParams, function (error, result) {
            if (error) throw error;
            let resultElement = result[0];
            if (body.name) {
                resultElement.name = body.name;
            }
            if (body.headImage) {
                resultElement.head_image = body.headImage;
            }
            if (body.phone) {
                resultElement.phone = body.phone;
            }
            if (body.pwd) {
                resultElement.pwd = body.pwd;
            }
            if (body.email) {
                resultElement.email = body.email;
            }
            const modSql = 'update user set name = ?,head_image = ?,phone = ?,pwd = ?,email =? where id = ?';
            const modSqlParams = [resultElement.name, resultElement.head_image, resultElement.phone, resultElement.pwd, resultElement.email, resultElement.id];
            connection.query(modSql, modSqlParams, function (err, result) {
                if (err) {
                    return result;
                }
                res.send('update success ' + result.affectedRows + ' row');
            });
        });
    });
})
// 删除用户
app.delete('/deleteuser', function (req, res) {
    console.log('-------------------------------');
    let body = '';
    req.on('data', function (chunk) {
        body += chunk;
    })
    req.on('end', function () {
        body = querystring.parse(body);
        if (!body.id) {
            res.send('参数错误');
            return;
        }
        const deleteSql = 'delete from user where id = ?';
        const deleteParams = [body.id];
        connection.query(deleteSql, deleteParams, function (error, result) {
            if (error) return;
            res.send('delete success ' + result.affectedRows + ' row');
        })

    })

})
// 开启服务
const server = app.listen(8081, function () {

    const host = server.address().address;
    const port = server.address().port;

    console.log("应用实例,访问地址为 http://%s:%s", host, port)

});
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161