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开发模式
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);
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |