NodeJS学习笔记

NodeJS软件安装

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

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

NodeJS在REPL模式和编辑器使用

windos在dos下常用命令

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开发模式

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常用命令

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模块
在这里插入图片描述

安装模块
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、同步操作文件

// 加载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);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/982929.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

阿里云QwQ-32B模型发布:AI领域的新突破

在人工智能技术飞速发展的今天&#xff0c;每一次重大突破都可能改写行业的未来。近日&#xff0c;阿里云重磅发布通义千问 QwQ-32B 模型&#xff0c;这一消息如同一颗重磅炸弹&#xff0c;瞬间在 AI 领域掀起轩然大波&#xff0c;引发全球关注。 QwQ-32B 模型的惊艳之处&…

HarmonyOS NEXT开发实战:DevEco Studio中DeepSeek的使用

随着HarmonyOS Next的持续发布&#xff0c;鸿蒙系统对AI能力的支持显著增强。本文将深入探讨如何在鸿蒙应用中集成AI模型&#xff0c;结合接入DeepSeek&#xff0c;一起来探索开发鸿蒙原生应用的更多可能吧&#xff01; 第一步&#xff1a;安装使用 建议使用DevEco Studio 5.0…

VMware 安装部署RHEL9

目录 目标一&#xff1a;创建名为RHEL9_node2的虚拟机 1.环境搭建&#xff1a;VMware 2.下载RHEL9的ISO镜像&#xff08;官网可获取&#xff09; 3.打开VMware&#xff0c;新建虚拟机 3.1 自定义安装 3.2 默认操纵至下一步操作到稍后安装系统 3.3选择操作系统为linux以及…

基于Python实现的智能旅游推荐系统(Django)

基于Python实现的智能旅游推荐系统(Django) 开发语言:Python 数据库&#xff1a;MySQL所用到的知识&#xff1a;Django框架工具&#xff1a;pycharm、Navicat 系统功能实现 总体设计 系统实现 系统首页模块 统首页页面主要包括首页&#xff0c;旅游资讯&#xff0c;景点信息…

利用可变参数模板,可打印任意参数和参数值。(C++很好的调式函数)

很酷的应用&#xff1a; &#xff08;1&#xff09; 如何获取可变参数名 代码例子&#xff1a; #define _test(...) (test_t(#__VA_ARGS__, __VA_ARGS__))template<typename... Args> void test_t(const char* names, Args... args) {std::cout << names <<…

HarmonyOS 应用程序包结构 (编译态)

不同类型的Module编译后会生成对应的HAP、HAR、HSP等文件&#xff0c;开发态视图与编译态视图的对照关系如下&#xff1a; 从开发态到编译态&#xff0c;Module中的文件会发生如下变更&#xff1a; ets目录&#xff1a;ArkTS源码编译生成.abc文件。resources目录&#xff1a;A…

After Effects的图钉与关键帧动画

姜 子 博 引言 在数字媒体时代&#xff0c;动态图形和视觉效果在信息传播和表达中扮演着越来越重要的角色。After Effects 作为行业领先的软件&#xff0c;提供了丰富的工具和功能&#xff0c;帮助用户创作出令人惊叹的视觉作品。图钉工具和关键帧动画是 AE 中实现复杂动画效…

共享模型之管程(悲观锁)

共享模型之管程&#xff08;悲观锁&#xff09; 文章目录 共享模型之管程&#xff08;悲观锁&#xff09;一、常见线程安全的类二、对象头三、Monitor&#xff08;监视器 / 管程&#xff09;四、偏向锁偏向锁的实现原理撤销偏向锁 五、轻量级锁轻量级锁的释放 六、重量级锁七、…

upload-labs详解(13-20)文件上传分析

目录 upload-labs-env upload-labs-env第十三关 文件包含漏洞 代码 测试 上传一个.jpg图片 上传一个.png文件 上传一个.gif图片 upload-labs-env第十四关 代码 思路 upload-labs-env第十五关 代码 思路 upload-labs-env第十六关 代码 思路 测试 上传gif格式…

探索高性能AI识别和边缘计算 | NVIDIA Jetson Orin Nano 8GB 开发套件的全面测评

随着边缘计算和人工智能技术的迅速发展&#xff0c;性能强大的嵌入式AI开发板成为开发者和企业关注的焦点。NVIDIA近期推出的Jetson Orin Nano 8GB开发套件&#xff0c;凭借其40 TOPS算力、高效的Ampere架构GPU以及出色的边缘AI能力&#xff0c;引起了广泛关注。本文将从配置性…

字典树(trie树)详解

【本文概要】本文主要介绍了字典树的概念&#xff0c;字典树的一般算法&#xff0c;包括初始化&#xff0c;插入&#xff0c;查找等&#xff0c;最后举了比较典型的案例来辅助理解字典树这种特殊的数据结构。 1、什么是字典树 字典树&#xff0c;是一种特殊的树状数据结构&…

从CL1看生物计算机的创新突破与发展前景:技术、应用与挑战的多维度剖析

一、引言 1.1 研究背景与意义 随着科技的飞速发展&#xff0c;计算机技术已经成为推动现代社会进步的核心力量之一。从最初的电子管计算机到如今的大规模集成电路计算机&#xff0c;计算机的性能得到了极大的提升&#xff0c;应用领域也不断拓展。然而&#xff0c;传统计算机…

小兔鲜Vue3

counterStore里面包含着对象返回的东西。 getters就是conputer git initgit add .git commit -m " " jsconfig进行路径提示。vite.config.js进行实际路径转化。 第一个文件做好就是一个axios实例了&#xff0c;可以直接调用方法。 在第二个文件是实例.get 写好路…

驱动 AI 边缘计算新时代!高性能 i.MX 95 应用平台引领未来

智慧浪潮崛起&#xff1a;AI与边缘计算的时代 正悄然深植于我们的日常生活之中&#xff0c;无论是火热的 ChatGPT 与 DeepSeek 语言模型&#xff0c;亦或是 Meta 智能眼镜&#xff0c;AI 技术已经无形地影响着我们的生活。这股变革浪潮并未停歇&#xff0c;而是进一步催生了更高…

STM32之软件SPI

SPI传输更快&#xff0c;最大可达80MHz&#xff0c;而I2C最大只有3.4MHz。输入输出是分开的&#xff0c;可以同时输出输入。是同步全双工。仅支持一主多从。SS是从机选择线。每个从机一根。SPI无应答机制的设计。 注意&#xff1a;所有设备需要共地&#xff0c;时钟线主机输出&…

深度学习系列79:Text2sql调研

参考 https://github.com/topics/text-to-sql 这里是一些资源&#xff1a;https://github.com/eosphoros-ai/Awesome-Text2SQL/blob/main/README.zh.md 这里是综述文章&#xff1a;https://zhuanlan.zhihu.com/p/647249972 1. 数据集 Spider: 一个跨域的复杂text2sql数据集&a…

【Unity】 HTFramework框架(六十一)Project窗口文件夹锁定器

更新日期&#xff1a;2025年3月7日。 Github源码&#xff1a;[点我获取源码] Gitee源码&#xff1a;[点我获取源码] 索引 Project窗口文件夹锁定器框架文件夹锁定自定义文件夹锁定限制条件 Project窗口文件夹锁定器 在Project窗口中&#xff0c;文件夹锁定器能够为任何文件夹加…

nginx服务器实现上传文件功能_使用nginx-upload-module模块

目录 conf文件内容如下html文件内容如下上传文件功能展示 conf文件内容如下 #user nobody; worker_processes 1;error_log /usr/logs/error.log; #error_log /usr/logs/error.log notice; #error_log /usr/logs/error.log info;#pid /usr/logs/nginx.pid;even…

基于云的内容中台核心优势是什么?

弹性云架构赋能资源整合 现代企业通过弹性云架构实现多源数据资源的深度整合&#xff0c;其动态扩展能力可自动适配业务流量波动。基于分布式存储与容器化部署&#xff0c;系统能够无缝对接CRM、ERP等企业软件集成&#xff0c;实现跨平台数据实时同步。值得注意的是&#xff0…

*图论基础(5)

持续更新... 1.图的基本概念 不写了&#xff0c;网上有好多资料ovo 2.图的存储和遍历 2.1存储&#xff1a; 3.最小生成树 3.2Kruskal算法 4.拓扑排序 拓扑排序的⽬标是将有向⽆环图中的所有结点排序&#xff0c;使得排在前⾯的结点不能依赖于排在后⾯的结 点。在课程问题中…