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
退出dos4、mkdir
创建命令5、dir
查看文件6、rmdir
删除目录7、ipconfig
查看IP8、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 mysql2、使用 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.urlif(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; // 获取请求的 URLconst parsedUrl = url.parse(uri); // 解析 URLconst 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);

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

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unity 实现在模型表面进行绘画

Texture2D-SetPixels32 - Unity 脚本 API 实现思路 从笔尖位置发射射线获取画纸上碰撞位置的UV 纹理坐标以确认笔迹位置&#xff0c;射线检查碰撞的最大距离即笔尖距离画纸的最大距离&#xff0c;利用Texture2D.SetPixels32 实现对画纸贴图颜色的修改。 核心代码 发射一条以…

2008-2024年中国手机基站数据/中国移动通信基站数据

2008-2024年中国手机基站数据/中国移动通信基站数据 1、时间&#xff1a;2008-2024年 2、来源&#xff1a;OpenCelliD 3、指标&#xff1a;网络类型、网络代数、移动国家/地区、移动网络代码、区域代码、小区标识、单元标识、坐标经度、坐标纬度、覆盖范围、测量样本数、坐标…

LeetCode Hot100刷题——反转链表(迭代+递归)

206.反转链表 给你单链表的头节点 head &#xff0c;请你反转链表&#xff0c;并返回反转后的链表。 示例 1&#xff1a; 输入&#xff1a;head [1,2,3,4,5] 输出&#xff1a;[5,4,3,2,1]示例 2&#xff1a; 输入&#xff1a;head [1,2] 输出&#xff1a;[2,1]示例 3&#…

Android项目优化同步速度

最近项目需要使用ffmpeg&#xff0c;需要gradle配置引入ffmpeg库&#xff0c;发现原来通过google官方的代码仓&#xff0c;下载太慢了&#xff0c;每秒KB级别的速度。&#xff08;之前下gradle/gradle plugin都不至于这么慢&#xff09;&#xff0c;于是想到配置国内镜像源来提…

Upload-Labs-Linux 1-20

前端校验绕过&#xff1a;pass 01 两种思路&#xff1a;1.通过抓包&#xff0c;修改后缀 2.前端禁用js绕过前端后缀检验 首先写一个木马&#xff0c;改为图片格式GIF89a<?php eval($_POST[cmd])?>抓包之后改为PHP格式&#xff1a; 使用蚁剑连接木马&#xff0c;第一次尝…

爬虫案例九js逆向爬取CBA中国篮球网

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、CBA网站分析二、代码 前言 提示&#xff1a;这里可以添加本文要记录的大概内容&#xff1a; 爬取CBA中国篮球网 提示&#xff1a;以下是本篇文章正文内容…

江科大51单片机笔记【10】蜂鸣器(上)

一、蜂鸣器 1.原理 蜂鸣器是一种将电信号转换为声音信号的器件&#xff0c;常同来产生设备的按键音、报警音等提示信号蜂鸣器按驱动方式可分为有源蜂鸣器和无源蜂鸣器&#xff08;外观基本一样&#xff09;有源蜂鸣器&#xff1a;内部自带振荡源&#xff0c;将正负极接上直流…

VS Code连接服务器教程

VS Code是什么 VS Code&#xff08;全称 Visual Studio Code&#xff09;是一款由微软推出的免费、开源、跨平台的代码编辑神器。VS Code 支持 所有主流操作系统&#xff0c;拥有强大的功能和灵活的扩展性。 官网&#xff1a;https://code.visualstudio.com/插件市场&#xff1…

使用QT + 文件IO + 鼠标拖拽事件 + 线程 ,实现大文件的传输

第一题、使用qss&#xff0c;通过线程&#xff0c;使进度条自己动起来 mythread.h #ifndef MYTHREAD_H #define MYTHREAD_H#include <QObject> #include <QThread> #include <QDebug>class mythread : public QThread {Q_OBJECT public:mythread(QObject* …

本地搭建DeepSeek R1模型 + 前端

本地搭建DeepSeek R1模型 前端 配置&#xff1a; 操作系统&#xff1a;windows11 CPU&#xff1a;i5 13600KF GPU&#xff1a;英伟达4070 12GB 内存&#xff1a;16G DDR5 硬盘&#xff1a;1TB 模型安装 本文采用Ollama进行安装。Ollama安装比较简单。 官网&#xff1…

[项目]基于FreeRTOS的STM32四轴飞行器: 五.Motor驱动

基于FreeRTOS的STM32四轴飞行器: 五.Motor驱动 一.配置CubeMX二.Motor驱动3.bug修改 一.配置CubeMX 观察motor原理图引脚对应的TIM&#xff1a; 使用内部时钟&#xff0c;配置4分频&#xff0c;后为18M&#xff0c;在设置Counter Period为1000-1&#xff0c;之后频率为18K&am…

Electron-Forge + Vue3 项目初始化

本人对Electron的浅薄理解如下图所示 由上图可以&#xff0c;如果你需要开发一个electron应用&#xff0c;你得具备基本的前端开发经验。对于electron相关的知识&#xff0c;建议先了解下基本的窗口操作&#xff0c;比如新建窗口、关闭窗口等简单的操作&#xff0c;这些内容在…

神经网络为什么要用 ReLU 增加非线性?

在神经网络中使用 ReLU&#xff08;Rectified Linear Unit&#xff09; 作为激活函数的主要目的是引入非线性&#xff0c;这是神经网络能够学习复杂模式和解决非线性问题的关键。 1. 为什么需要非线性&#xff1f; 1.1 线性模型的局限性 如果神经网络只使用线性激活函数&…

手写Tomcat:实现基本功能

首先&#xff0c;Tomcat是一个软件&#xff0c;所有的项目都能在Tomcat上加载运行&#xff0c;Tomcat最核心的就是Servlet集合&#xff0c;本身就是HashMap。Tomcat需要支持Servlet&#xff0c;所以有servlet底层的资源&#xff1a;HttpServlet抽象类、HttpRequest和HttpRespon…

PyTorch系列教程:编写高效模型训练流程

当使用PyTorch开发机器学习模型时&#xff0c;建立一个有效的训练循环是至关重要的。这个过程包括组织和执行对数据、参数和计算资源的操作序列。让我们深入了解关键组件&#xff0c;并演示如何构建一个精细的训练循环流程&#xff0c;有效地处理数据处理&#xff0c;向前和向后…

Linux系统基于ARM平台的LVGL移植

软硬件介绍&#xff1a;Ubuntu 20.04 ARM 和&#xff08;Cortex-A53架构&#xff09;开发板 基本原理 LVGL图形库是支持使用Linux系统的Framebuffer帧缓冲设备实现的&#xff0c;如果想要实现在ARM开发板上运行LVGL图形库&#xff0c;那么就需要把LVGL图形库提供的关于帧缓冲设…

Consensus 大会全观察:政策、生态与技术交汇,香港能否抢占 Web3 先机?

被誉为 “区块链界超级碗” 和 “Web3 世界杯” 的全球顶级行业峰会 —— Consensus 大会&#xff0c;在诞生十年之际首次跨越太平洋登陆亚洲&#xff0c;于 2025 年 2 月 18 日至 20 日在香港会议展览中心盛大启幕。大会汇聚了亚洲主要金融政策制定者、加密领域思想领袖、投资…

hadoop集群环境配置

目录 VMware虚拟机安装 Xshell安装 网络问题 centos7下载 ---------参考以下视频步骤进行生态搭建---------- 搭建好hadoop01 克隆出hadoop02、hadoop03 启动三台虚拟机 打开终端 输入 记录下各个ip 打开Xshell&#xff0c;新建会话 修改主机名 配置静态IP 主机名称…

C++之list

list是链表的意思&#xff0c;由一个个节点组成 一、基本接口使用&#xff1a; &#xff08;1&#xff09;与vector相同&#xff0c;有个尾插&#xff0c;也可以使用迭代器遍历&#xff1a; void test_list1() {list<int> lt;lt.push_back(1);lt.push_back(2);lt.push…

MWC 2025 | 紫光展锐联合移远通信推出全面支持R16特性的5G模组RG620UA-EU

2025年世界移动通信大会&#xff08;MWC 2025&#xff09;期间&#xff0c;紫光展锐联合移远通信&#xff0c;正式发布了全面支持5G R16特性的模组RG620UA-EU&#xff0c;以强大的灵活性和便捷性赋能产业。 展锐芯加持&#xff0c;关键性能优异 RG620UA-EU模组基于紫光展锐V62…