目录

NodeJS学习笔记

NodeJS学习笔记

NodeJS软件安装

node环境安装
https://nodejs.org
安装好后的node通常在C:\Program Files\nodejs

验证安装是否成功
node -v
npm -v 
进入REPL模式命令行模式
node

NodeJS在REPL模式和编辑器使用

windos在dos下常用命令

windos命令
1cmd
dos系统

2cls
清空屏幕

3exit
退出dos

4mkdir
创建命令

5dir
查看文件

6rmdir
删除目录

7ipconfig
查看IP

8ping
通讯测试

9start http://www.baidu.com
打开浏览器

10tasklist
查看进程

11taskkill /f /im chrome.exe
关闭进程

12cd
切换目录

13netstat -ano|find "8080"
查看指定端口

node repl开发模式

cmd下执行js文件
node index.js

NPM国内镜像设置

1使用国内镜像源靠谱亲测可以下载mysql
 npm 的默认源替换为国内镜像源如淘宝镜像),可以显著提升下载速度
npm config set registry https://registry.npmmirror.com
验证是否生效
npm config get registry
安装 mysql
npm install mysql

2使用 cnpm
cnpm 是淘宝镜像提供的 npm 客户端默认使用淘宝镜像源适合国内开发者
npm install -g cnpm --registry=https://registry.npmmirror.com
使用 cnpm 安装 mysql
cnpm install mysql

NPM模块库、WEB应用和回调函数

npm常用命令

1npm list
查看本地模块

2npm install mysql
安装mysql模块

3npm uninstall mysql
卸载mysql模块

4npm root
本地模块根目录

5npm root -g
本地服务器所有模块根目录

6npm update mysql
升级指定npm包

node中创建第一个应用(WEB服务)

1、加载http web模块

https://i-blog.csdnimg.cn/direct/5e9cf339a6f44e83bef52f6546d2b860.png

安装模块
npm install express

//1、加载http web模块
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
    res.write("<h1>测试123</h1>");
    res.send(); // 使用 res.send() 发送响应
});

app.listen(666, () => {
    console.log('server is running');
});

2、查找运行的端口号,找到对应的进程ID

https://i-blog.csdnimg.cn/direct/43e8912beeca499bb6989d13ae05ea46.png

3、根据进程ID找到对应的进程

https://i-blog.csdnimg.cn/direct/fa710724b29e48e8a91184cd6ffb4748.png

4、访问:

http://localhost:666/

node回调函数

1、同步操作文件

// 加载fs file模块
const fs = require('fs')
file = 'test.txt'
//开始读取文件
console.log('准备读取文件');

//正在读取文件
data = fs.readFileSync(file)
console.log(data.toString())

//读取文件结束
console.log('程序执行结束')

2、异步操作文件

// 加载fs file模块
const fs = require('fs')
file = 'test.txt'
//开始读取文件
console.log('准备读取文件');

//正在读取文件
fs.readFile(file,function(err,data){
    console.log(data.toString())
});

//读取文件结束
console.log('程序执行结束')

Event事件、模块、函数和路由

event事件循环

const events = require('events'); // 导入 events 模块
const evt = new events.EventEmitter(); // 初始化 EventEmitter 实例

function eventHandler() {
    console.log('123'); // 事件处理函数
}

evt.on('eventName', eventHandler); // 监听事件
evt.emit('eventName'); // 触发事件

模块系统

######show.js代码块

// 自定义show模块
//函数里含有this,则该函数可以称为类
function show(){
    this.name =  'user1';
    this.say = function(){
        console.log('my name is ' + this.name);
    }
}

// 导出show模块,然后在index.js中引入使用
module.exports = show;


######index.js代码块使用
const show = require('./show.js');
obj = new show();
obj.say();

function函数

1常用函数
function aa(){
    console.log(123);
}
2匿名函数
aa = function(){
    console.log(123);
}

路由

const http = require('http');
const url = require('url');

cs = function(req,res){
    res.writeHead(200,{'Content-Type':'text/plain;utf-8'});
    uri = req.url;
    if(uri != '/favicon.ico'){
     
        //解析路由
        path = url.parse(uri,true).pathname;
        switch(path){
            case '/user/add':
                res.write('add');
                break;
            case '/user/list':
                res.write('list');
                break;
            default:
                res.write('404');
        }
    }
    
    res.end();
}

http.createServer(cs).listen(8888);

NodeJS全局对象

node全局对象
console.log(__filename);

console.log(__dirname);

setTimeout(function(){
console.log(123)
},1000)

setTimeout(function(){
console.log(123)
},1000)

console.log()

计算程序执行时间
const start = performance.now();
for(let i = 0; i < 100000000; i++) {
    // 空循环
}
const end = performance.now();
console.log(`Execution time: ${end - start} milliseconds`);

查看进程相信信息
str = process.version;
str = process.arch;
console.log(str);

NodeJS文件系统、GET请求和工具模块

文件系统

1、读文件内容

1)异步读取 readFile() 示例:

//加载文件处理模块
const fs = require('fs');
file = 'test.txt';
//同步读取
fs.readFile(file,function(err,data){
    str = data.toString();
    console.log(str);
})
console.log('读取文件内容');

2)同步阻塞读取 readFileSync()示例:

//加载文件处理模块
const fs = require('fs');
file = 'test.txt';
//同步读取
data  = fs.readFileSync(file)
str = data.toString();
console.log(str);

2、写文件内容

const fs = require('fs');
const file = 'test.txt';
const str = '\n11111';

fs.appendFile(file, str, 'utf8', (err) => {
    if (err) {
        console.error('追加文件内容时出错:', err);
    } else {
        console.log('内容追加成功');
    }
});

3、删除文件 unlink()示例:

const fs = require('fs');
const file = 'test.txt';

if (fs.existsSync(file)) {
    fs.unlink(file, (err) => {
        if (err) {
            console.error('删除文件时出错:', err);
        } else {
            console.log('文件删除成功');
        }
    });
} else {
    console.log('文件不存在');
}

4、创建目录 mkdir()示例:

const fs = require('fs');
const dir = 'myweb';
if (!fs.existsSync(dir)) {
    fs.mkdir(dir, (err) => {
        if (err) {
            console.error('创建目录时出错:', err);
        } else {
            console.log('目录创建成功');
        }
    });
} else {
    console.log('目录已存在');
}

5、删除目录 rmdir()

get请求

http = require('http');
url = require('url');
querystring = require('querystring');

cs = function(req,res) {
    uri = req.url
    if(uri !='/favicon.ico'){
        str = url.parse(uri).query;
        json = querystring.parse(str);
        console.log(json);
        res.write(JSON.stringify(json));
    }
    res.end();
}

http.createServer(cs).listen(8000);
console.log('server is running');

工具模块

##os模块
const os = require('os');
console.log(os.platform())

##path模块
const path = require('path');
str = '/user/local/www/index.sh';
console.log(path.extname(str))

实战

1、php操作删除数据库

index.php

<?php
// 创建连接
$conn = new mysqli("localhost", "root", "root", "myweb");
// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 设置字符集
$conn->set_charset("utf8");

// 执行查询
$sql = "SELECT * FROM user";
$ret = $conn->query($sql);

// 检查查询结果
if (!$ret) {
    echo "查询失败: " . $conn->error;
}

// 关闭连接
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            font-family: 微软雅黑;
        }
    </style>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">查看用户:</h2>
        <table class="table table-bordered table-hover">
            <tr>
                <th>编号</th>
                <th>用户名</th>
                <th>密码</th>
                <th>删除</th>
            </tr>
            <?php 
            while ($row = $ret->fetch_assoc()) {
                echo "<tr>";
                echo "<td>" . $row["id"] . "</td>";
                echo "<td>" . $row["username"] . "</td>";
                echo "<td>" . $row["password"] . "</td>";
                echo "<td><a href='#' class='del' id='{$row['id']}'>删除</></td>";
                echo "</tr>";
            }
            ?>
        </table>
    </div>
</body>
<script>
    $('.del').click(function(){
        let id = $(this).attr('id');
        let row = $(this).closest('tr'); // 保存当前行的引用
        $.get('del.php',{id:id},function(data){
            if(data == 1){
                row.hide(); 
            }else{
                alert('删除失败');
            }
        })
    })
</script>
</html>

del.php

<?php
// 创建连接
$conn = new mysqli("localhost", "root", "root", "myweb");
// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 设置字符集
$conn->set_charset("utf8");

// 执行查询
$id = $_GET['id'];
$sql = "DELETE FROM user WHERE id = {$id}";
$ret = $conn->query($sql);

// 检查查询结果
if (!$ret) {
    echo "删除失败: " . $conn->error;
}else{
    echo 1;
}

// 关闭连接
$conn->close();

2、node操作删除数据库

index.php

<?php
// 创建连接
$conn = new mysqli("localhost", "root", "root", "myweb");
// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 设置字符集
$conn->set_charset("utf8");

// 执行查询
$sql = "SELECT * FROM user";
$ret = $conn->query($sql);

// 检查查询结果
if (!$ret) {
    echo "查询失败: " . $conn->error;
}

// 关闭连接
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            font-family: 微软雅黑;
        }
    </style>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">查看用户:</h2>
        <table class="table table-bordered table-hover">
            <tr>
                <th>编号</th>
                <th>用户名</th>
                <th>密码</th>
                <th>删除</th>
            </tr>
            <?php 
            while ($row = $ret->fetch_assoc()) {
                echo "<tr>";
                echo "<td>" . $row["id"] . "</td>";
                echo "<td>" . $row["username"] . "</td>";
                echo "<td>" . $row["password"] . "</td>";
                echo "<td><a href='#' class='del' id='{$row['id']}'>删除</></td>";
                echo "</tr>";
            }
            ?>
        </table>
    </div>
</body>
<script>
    $('.del').click(function(){
        let id = $(this).attr('id');
        let row = $(this).closest('tr'); // 保存当前行的引用
        $.getJSON('http://localhost:8888?cb=?', {id:id}, function(json){
            if(json.ok == 1){
                row.remove(); // 删除当前行
            }else{
                alert('删除失败');
            }
        })
    })
</script>
</html>

index.js

const http = require('http');
const url = require('url');
const querystring = require('querystring');
const mysql = require('mysql');

const cs = function (req, res) {
    const uri = req.url; // 获取请求的 URL
    const parsedUrl = url.parse(uri); // 解析 URL
    const json = querystring.parse(parsedUrl.query); // 解析查询字符串
    fname = json.cb;
    id = json.id;
    jsonstr = fname + '({"ok":"1"})';
    //连接操作数据库
    const connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        database: 'myweb'
    });
    connection.connect();
    connection.query('DELETE FROM user WHERE id = ?', [id], function (error, rs, fields) {
        if(rs.affectedRows == 1){
            res.write(jsonstr);
            res.end();
        }
    });
    //关闭数据库
    connection.end();
};

http.createServer(cs).listen(8888);