NodeJS学习条记

打印 上一主题 下一主题

主题 1847|帖子 1847|积分 5551

NodeJS软件安装

  1. node环境安装:
  2. https://nodejs.org
  3. 安装好后的node通常在C:\Program Files\nodejs
  4. 验证安装是否成功
  5. node -v
  6. npm -v
  7. 进入REPL模式命令行模式
  8. node
复制代码
NodeJS在REPL模式和编辑器使用

windos在dos下常用下令
  1. windos命令:
  2. 1、cmd
  3. dos系统
  4. 2、cls
  5. 清空屏幕
  6. 3、exit
  7. 退出dos
  8. 4、mkdir
  9. 创建命令
  10. 5、dir
  11. 查看文件
  12. 6、rmdir
  13. 删除目录
  14. 7、ipconfig
  15. 查看IP
  16. 8、ping
  17. 通讯测试
  18. 9、start http://www.baidu.com
  19. 打开浏览器
  20. 10、tasklist
  21. 查看进程
  22. 11、taskkill /f /im chrome.exe
  23. 关闭进程
  24. 12、cd
  25. 切换目录
  26. 13、netstat -ano|find "8080"
  27. 查看指定端口
复制代码
node repl开发模式
  1. cmd下执行js文件
  2. node index.js
复制代码
NPM国内镜像设置

  1. 1、使用国内镜像源(靠谱,亲测可以下载mysql)
  2. 将 npm 的默认源替换为国内镜像源(如淘宝镜像),可以显著提升下载速度。
  3. npm config set registry https://registry.npmmirror.com
  4. 验证是否生效:
  5. npm config get registry
  6. 安装 mysql:
  7. npm install mysql
  8. 2、使用 cnpm
  9. cnpm 是淘宝镜像提供的 npm 客户端,默认使用淘宝镜像源,适合国内开发者。
  10. npm install -g cnpm --registry=https://registry.npmmirror.com
  11. 使用 cnpm 安装 mysql:
  12. cnpm install mysql
复制代码
NPM模块库、WEB应用和回调函数

npm常用下令
  1. 1、npm list
  2. 查看本地模块
  3. 2、npm install mysql
  4. 安装mysql模块
  5. 3、npm uninstall mysql
  6. 卸载mysql模块
  7. 4、npm root
  8. 本地模块根目录
  9. 5、npm root -g
  10. 本地服务器所有模块根目录
  11. 6、npm update mysql
  12. 升级指定npm包
复制代码
node中创建第一个应用(WEB服务)
1、加载http web模块

  1. 安装模块
  2. npm install express
  3. //1、加载http web模块
  4. const express = require('express');
  5. const app = express();
  6. app.get('/', (req, res) => {
  7.     res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
  8.     res.write("<h1>测试123</h1>");
  9.     res.send(); // 使用 res.send() 发送响应
  10. });
  11. app.listen(666, () => {
  12.     console.log('server is running');
  13. });
复制代码
2、查找运行的端标语,找到对应的历程ID

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

4、访问:
http://localhost:666/
node回调函数
1、同步操作文件
  1. // 加载fs file模块
  2. const fs = require('fs')
  3. file = 'test.txt'
  4. //开始读取文件
  5. console.log('准备读取文件');
  6. //正在读取文件
  7. data = fs.readFileSync(file)
  8. console.log(data.toString())
  9. //读取文件结束
  10. console.log('程序执行结束')
复制代码
2、异步操作文件
  1. // 加载fs file模块
  2. const fs = require('fs')
  3. file = 'test.txt'
  4. //开始读取文件
  5. console.log('准备读取文件');
  6. //正在读取文件
  7. fs.readFile(file,function(err,data){
  8.     console.log(data.toString())
  9. });
  10. //读取文件结束
  11. console.log('程序执行结束')
复制代码
Event事件、模块、函数和路由

event事件循环
  1. const events = require('events'); // 导入 events 模块
  2. const evt = new events.EventEmitter(); // 初始化 EventEmitter 实例
  3. function eventHandler() {
  4.     console.log('123'); // 事件处理函数
  5. }
  6. evt.on('eventName', eventHandler); // 监听事件
  7. evt.emit('eventName'); // 触发事件
复制代码
模块体系
  1. ######show.js代码块
  2. // 自定义show模块
  3. //函数里含有this,则该函数可以称为类
  4. function show(){
  5.     this.name =  'user1';
  6.     this.say = function(){
  7.         console.log('my name is ' + this.name);
  8.     }
  9. }
  10. // 导出show模块,然后在index.js中引入使用
  11. module.exports = show;
  12. ######index.js代码块使用
  13. const show = require('./show.js');
  14. obj = new show();
  15. obj.say();
复制代码
function函数
  1. 1、常用函数
  2. function aa(){
  3.     console.log(123);
  4. }
  5. 2、匿名函数
  6. aa = function(){
  7.     console.log(123);
  8. }
复制代码
路由
  1. const http = require('http');
  2. const url = require('url');
  3. cs = function(req,res){
  4.     res.writeHead(200,{'Content-Type':'text/plain;utf-8'});
  5.     uri = req.url;
  6.     if(uri != '/favicon.ico'){
  7.      
  8.         //解析路由
  9.         path = url.parse(uri,true).pathname;
  10.         switch(path){
  11.             case '/user/add':
  12.                 res.write('add');
  13.                 break;
  14.             case '/user/list':
  15.                 res.write('list');
  16.                 break;
  17.             default:
  18.                 res.write('404');
  19.         }
  20.     }
  21.    
  22.     res.end();
  23. }
  24. http.createServer(cs).listen(8888);
复制代码
NodeJS全局对象

  1. node全局对象:
  2. console.log(__filename);
  3. console.log(__dirname);
  4. setTimeout(function(){
  5. console.log(123)
  6. },1000)
  7. setTimeout(function(){
  8. console.log(123)
  9. },1000)
  10. console.log()
  11. 计算程序执行时间
  12. const start = performance.now();
  13. for(let i = 0; i < 100000000; i++) {
  14.     // 空循环
  15. }
  16. const end = performance.now();
  17. console.log(`Execution time: ${end - start} milliseconds`);
  18. 查看进程相信信息
  19. str = process.version;
  20. str = process.arch;
  21. console.log(str);
复制代码
NodeJS文件体系、GET哀求和工具模块

文件体系
  1. 1、读文件内容
  2. 1)异步读取
  3. readFile()
  4. ##示例:
  5. //加载文件处理模块
  6. const fs = require('fs');
  7. file = 'test.txt';
  8. //同步读取
  9. fs.readFile(file,function(err,data){
  10.     str = data.toString();
  11.     console.log(str);
  12. })
  13. console.log('读取文件内容');
  14. 2)同步阻塞读取
  15. readFileSync()
  16. ##示例:
  17. //加载文件处理模块
  18. const fs = require('fs');
  19. file = 'test.txt';
  20. //同步读取
  21. data  = fs.readFileSync(file)
  22. str = data.toString();
  23. console.log(str);
  24. 2、写文件内容
  25. const fs = require('fs');
  26. const file = 'test.txt';
  27. const str = '\n11111';
  28. fs.appendFile(file, str, 'utf8', (err) => {
  29.     if (err) {
  30.         console.error('追加文件内容时出错:', err);
  31.     } else {
  32.         console.log('内容追加成功');
  33.     }
  34. });
  35. 3、删除文件
  36. unlink()
  37. ##示例:
  38. const fs = require('fs');
  39. const file = 'test.txt';
  40. if (fs.existsSync(file)) {
  41.     fs.unlink(file, (err) => {
  42.         if (err) {
  43.             console.error('删除文件时出错:', err);
  44.         } else {
  45.             console.log('文件删除成功');
  46.         }
  47.     });
  48. } else {
  49.     console.log('文件不存在');
  50. }
  51. 4、创建目录
  52. mkdir()
  53. ##示例:
  54. const fs = require('fs');
  55. const dir = 'myweb';
  56. if (!fs.existsSync(dir)) {
  57.     fs.mkdir(dir, (err) => {
  58.         if (err) {
  59.             console.error('创建目录时出错:', err);
  60.         } else {
  61.             console.log('目录创建成功');
  62.         }
  63.     });
  64. } else {
  65.     console.log('目录已存在');
  66. }
  67. 5、删除目录
  68. rmdir()
复制代码
get哀求
  1. http = require('http');
  2. url = require('url');
  3. querystring = require('querystring');
  4. cs = function(req,res) {
  5.     uri = req.url
  6.     if(uri !='/favicon.ico'){
  7.         str = url.parse(uri).query;
  8.         json = querystring.parse(str);
  9.         console.log(json);
  10.         res.write(JSON.stringify(json));
  11.     }
  12.     res.end();
  13. }
  14. http.createServer(cs).listen(8000);
  15. console.log('server is running');
复制代码
工具模块
  1. ##os模块
  2. const os = require('os');
  3. console.log(os.platform())
  4. ##path模块
  5. const path = require('path');
  6. str = '/user/local/www/index.sh';
  7. console.log(path.extname(str))
复制代码
实战

1、php操作删除数据库
index.php
  1. <?php
  2. // 创建连接
  3. $conn = new mysqli("localhost", "root", "root", "myweb");
  4. // 检查连接是否成功
  5. if ($conn->connect_error) {
  6.     die("连接失败: " . $conn->connect_error);
  7. }
  8. // 设置字符集
  9. $conn->set_charset("utf8");
  10. // 执行查询
  11. $sql = "SELECT * FROM user";
  12. $ret = $conn->query($sql);
  13. // 检查查询结果
  14. if (!$ret) {
  15.     echo "查询失败: " . $conn->error;
  16. }
  17. // 关闭连接
  18. $conn->close();
  19. ?>
  20. <!DOCTYPE html>
  21. <html lang="en">
  22. <head>
  23.     <meta charset="UTF-8">
  24.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  25.     <title>Document</title>
  26.     <style>
  27.         *{
  28.             font-family: 微软雅黑;
  29.         }
  30.     </style>
  31.     <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">
  32.     <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  33.     <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>
  34.     <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
  35. </head>
  36. <body>
  37.     <div class="container">
  38.         <h2 class="page-header">查看用户:</h2>
  39.         <table class="table table-bordered table-hover">
  40.             <tr>
  41.                 <th>编号</th>
  42.                 <th>用户名</th>
  43.                 <th>密码</th>
  44.                 <th>删除</th>
  45.             </tr>
  46.             <?php
  47.             while ($row = $ret->fetch_assoc()) {
  48.                 echo "<tr>";
  49.                 echo "<td>" . $row["id"] . "</td>";
  50.                 echo "<td>" . $row["username"] . "</td>";
  51.                 echo "<td>" . $row["password"] . "</td>";
  52.                 echo "<td><a href='#' class='del' id='{$row['id']}'>删除</></td>";
  53.                 echo "</tr>";
  54.             }
  55.             ?>
  56.         </table>
  57.     </div>
  58. </body>
  59. <script>
  60.     $('.del').click(function(){
  61.         let id = $(this).attr('id');
  62.         let row = $(this).closest('tr'); // 保存当前行的引用
  63.         $.get('del.php',{id:id},function(data){
  64.             if(data == 1){
  65.                 row.hide();
  66.             }else{
  67.                 alert('删除失败');
  68.             }
  69.         })
  70.     })
  71. </script>
  72. </html>
复制代码
del.php
  1. <?php
  2. // 创建连接
  3. $conn = new mysqli("localhost", "root", "root", "myweb");
  4. // 检查连接是否成功
  5. if ($conn->connect_error) {
  6.     die("连接失败: " . $conn->connect_error);
  7. }
  8. // 设置字符集
  9. $conn->set_charset("utf8");
  10. // 执行查询
  11. $id = $_GET['id'];
  12. $sql = "DELETE FROM user WHERE id = {$id}";
  13. $ret = $conn->query($sql);
  14. // 检查查询结果
  15. if (!$ret) {
  16.     echo "删除失败: " . $conn->error;
  17. }else{
  18.     echo 1;
  19. }
  20. // 关闭连接
  21. $conn->close();
复制代码
2、node操作删除数据库
index.php
  1. <?php
  2. // 创建连接
  3. $conn = new mysqli("localhost", "root", "root", "myweb");
  4. // 检查连接是否成功
  5. if ($conn->connect_error) {
  6.     die("连接失败: " . $conn->connect_error);
  7. }
  8. // 设置字符集
  9. $conn->set_charset("utf8");
  10. // 执行查询
  11. $sql = "SELECT * FROM user";
  12. $ret = $conn->query($sql);
  13. // 检查查询结果
  14. if (!$ret) {
  15.     echo "查询失败: " . $conn->error;
  16. }
  17. // 关闭连接
  18. $conn->close();
  19. ?>
  20. <!DOCTYPE html>
  21. <html lang="en">
  22. <head>
  23.     <meta charset="UTF-8">
  24.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  25.     <title>Document</title>
  26.     <style>
  27.         *{
  28.             font-family: 微软雅黑;
  29.         }
  30.     </style>
  31.     <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">
  32.     <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  33.     <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>
  34.     <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
  35. </head>
  36. <body>
  37.     <div class="container">
  38.         <h2 class="page-header">查看用户:</h2>
  39.         <table class="table table-bordered table-hover">
  40.             <tr>
  41.                 <th>编号</th>
  42.                 <th>用户名</th>
  43.                 <th>密码</th>
  44.                 <th>删除</th>
  45.             </tr>
  46.             <?php
  47.             while ($row = $ret->fetch_assoc()) {
  48.                 echo "<tr>";
  49.                 echo "<td>" . $row["id"] . "</td>";
  50.                 echo "<td>" . $row["username"] . "</td>";
  51.                 echo "<td>" . $row["password"] . "</td>";
  52.                 echo "<td><a href='#' class='del' id='{$row['id']}'>删除</></td>";
  53.                 echo "</tr>";
  54.             }
  55.             ?>
  56.         </table>
  57.     </div>
  58. </body>
  59. <script>
  60.     $('.del').click(function(){
  61.         let id = $(this).attr('id');
  62.         let row = $(this).closest('tr'); // 保存当前行的引用
  63.         $.getJSON('http://localhost:8888?cb=?', {id:id}, function(json){
  64.             if(json.ok == 1){
  65.                 row.remove(); // 删除当前行
  66.             }else{
  67.                 alert('删除失败');
  68.             }
  69.         })
  70.     })
  71. </script>
  72. </html>
复制代码
index.js
  1. const http = require('http');
  2. const url = require('url');
  3. const querystring = require('querystring');
  4. const mysql = require('mysql');
  5. const cs = function (req, res) {
  6.     const uri = req.url; // 获取请求的 URL
  7.     const parsedUrl = url.parse(uri); // 解析 URL
  8.     const json = querystring.parse(parsedUrl.query); // 解析查询字符串
  9.     fname = json.cb;
  10.     id = json.id;
  11.     jsonstr = fname + '({"ok":"1"})';
  12.     //连接操作数据库
  13.     const connection = mysql.createConnection({
  14.         host: 'localhost',
  15.         user: 'root',
  16.         password: 'root',
  17.         database: 'myweb'
  18.     });
  19.     connection.connect();
  20.     connection.query('DELETE FROM user WHERE id = ?', [id], function (error, rs, fields) {
  21.         if(rs.affectedRows == 1){
  22.             res.write(jsonstr);
  23.             res.end();
  24.         }
  25.     });
  26.     //关闭数据库
  27.     connection.end();
  28. };
  29. http.createServer(cs).listen(8888);
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

篮之新喜

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表