NodeJS学习笔记

NodeJS软件安装

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

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

NodeJS在REPL模式和编辑器使用

windos在dos下常用命令

bash 复制代码
windos命令:
1、cmd
dos系统

2、cls
清空屏幕

3、exit
退出dos

4、mkdir
创建命令

5、dir
查看文件

6、rmdir
删除目录

7、ipconfig
查看IP

8、ping
通讯测试

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

10、tasklist
查看进程

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

12、cd
切换目录

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

node repl开发模式

bash 复制代码
cmd下执行js文件
node index.js

NPM国内镜像设置

bash 复制代码
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常用命令

bash 复制代码
1、npm list
查看本地模块

2、npm install mysql
安装mysql模块

3、npm uninstall mysql
卸载mysql模块

4、npm root
本地模块根目录

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

6、npm update mysql
升级指定npm包

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

1、加载http web模块

bash 复制代码
安装模块
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

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

4、访问:

http://localhost:666/

node回调函数

1、同步操作文件

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

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

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

2、异步操作文件

bash 复制代码
// 加载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事件循环

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

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

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

模块系统

bash 复制代码
######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函数

bash 复制代码
1、常用函数
function aa(){
    console.log(123);
}
2、匿名函数
aa = function(){
    console.log(123);
}

路由

bash 复制代码
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全局对象

bash 复制代码
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请求和工具模块

文件系统

bash 复制代码
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请求

bash 复制代码
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');

工具模块

bash 复制代码
##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

bash 复制代码
<?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

bash 复制代码
<?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

bash 复制代码
<?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

bash 复制代码
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);
相关推荐
鱼樱前端2 分钟前
📚 Vue Router 4 核心知识点(Vue3技术栈)面试指南
前端·javascript·vue.js
食指Shaye8 分钟前
Chrome 中清理缓存的方法
前端·chrome·缓存
午后书香19 分钟前
一天三场面试,口干舌燥要晕倒(二)
前端·javascript·面试
Book_熬夜!34 分钟前
CSS—补充:CSS计数器、单位、@media媒体查询
前端·css·html·媒体
几度泥的菜花2 小时前
如何禁用移动端页面的多点触控和手势缩放
前端·javascript
狼性书生2 小时前
electron + vue3 + vite 渲染进程到主进程的双向通信
前端·javascript·electron
肥肠可耐的西西公主2 小时前
前端(AJAX)学习笔记(CLASS 4):进阶
前端·笔记·学习
拉不动的猪2 小时前
Node.js(Express)
前端·javascript·面试
Re.不晚2 小时前
Web前端开发——HTML基础下
前端·javascript·html
几何心凉2 小时前
如何处理前端表单验证,确保用户输入合法?
前端·css·前端框架