• nodejs学习week01


    说明:学习nodejs之气那应该掌握html,css,JavaScript等前端基础技术 

    目录

    一、什么是nodejs

    二、nodejs的内部模块

    1.fs文件系统模块

    2.path路径模块

    3.http服务器模块

    三、module.exports对象

    四、时间格式化

    1.使用JavaScript的方法

    2.使用moment对时间进行格式化

    五、案例 实现clock时钟的web服务器


    前言:从今天开始我们一起来学习nodejs相关知识。

     

    一、什么是nodejs

    nodejs 是一个基于Chrome V8引擎的JavaScript运行环境

    二、nodejs的内部模块

    1.fs文件系统模块

    readFile('文件路径绝/相对',‘字符集’,function(读取错误,读取成功{})):读取文件内容

     writeFile(‘路径’,‘内容’,function(err){})

      

    e.g:学上成绩转换

    1. const fs = require('fs')
    2. //读取文件
    3. //可以提供相对路径,也可以提供绝对路径(node会运行当下路径进行拼接)
    4. fs.readFile('./files/成绩.txt','utf8',function(err,dataStr){
    5. //判断是否能读取成功
    6. if(err){
    7. return console.log("读取失败"+err.message)
    8. }
    9. //将原数组按照空格分开
    10. const arrOld = dataStr.split(' ')
    11. console.log(arrOld)
    12. console.log('读取成功'+dataStr)
    13. //用:替换=并且加入到新数组中
    14. const arrNew = []
    15. arrOld.forEach(item => {
    16. arrNew.push(item.replace('=',': '))
    17. });
    18. console.log(arrNew)
    19. //向数组中新增空格换行符号
    20. const newStr = arrNew.join('\r\n')
    21. console.log(newStr)
    22. })

     

     

    2.path路径模块

     

     

    3.http服务器模块

    创建基本的服务器

    1. const http = require('http')
    2. const serever = http.createServer()
    3. //为服务器实例绑定request事件
    4. serever.on('request',function(req,res){
    5. console.log('Someone visit our web server')
    6. })
    7. //启动服务器监听(启动服务器)
    8. serever.listen(8080,function(){
    9. console.log('server running at http://127.0.0.1:8080')
    10. })

    req请求

    1. //req请求对象
    2. //req:访问与客户端有关的数据和属性
    3. //req.url:客户端请求的URL地址
    4. //req.method:客户端的method请求类型
    5. const http = require('http')
    6. const server = http.createServer()
    7. //req请求对象
    8. server.on('request',req=>{
    9. const url = req.url
    10. const method = req.method
    11. //输出
    12. const str = `Your request url is ${url}, and reqyest method is ${method}` //反引号
    13. console.log(str)
    14. })
    15. server.listen(8080,()=>{
    16. console.log('server running at http://127.0.0.1:8080')
    17. })

    res响应:

    1. const http = require('http')
    2. const server = http.createServer()
    3. //req请求对象
    4. server.on('request',(req,res)=>{
    5. const url = req.url
    6. const method = req.method
    7. //输出
    8. const str = `Your request url is ${url}, and reqyest method is ${method}` //反引号
    9. console.log(str)
    10. //调用res.end方法向客户端响应一些数据
    11. res.end(str)
    12. })
    13. server.listen(8080,()=>{
    14. console.log('server running at http://127.0.0.1:8080')
    15. })

    三、module.exports对象

    向外暴露模块中的属性和方法(相当于私有的被公开)

    自定义模块:

    1. console.log('加载了用户自定义模块')
    2. //向module.exports对象上挂载username属性
    3. module.exports.username = 'zz'
    4. //向module》exports上挂在
    5. module.exports.sayHello = function(){
    6. console.log("hello")
    7. }
    8. module.exports = {
    9. nickname:'小黑',
    10. sayHi(){
    11. console.log('hi')
    12. }
    13. }

     test

    1. //加载用户模块通过路径
    2. const a = require('./11.加载用户自定义模块')
    3. console.log(a)

     四、时间格式化

    1.使用JavaScript的方法

    dateformat.js

    1. //定义格式化时间的方法
    2. function dateFormat(dtStr){
    3. const dt = new Date(dtStr)
    4. //年
    5. const y = dt.getFullYear()
    6. //月
    7. const m = padZero(dt.getMonth()+1)
    8. //日
    9. const d = padZero(dt.getDay())
    10. //时
    11. const hh = padZero(dt.getHours())
    12. //分
    13. const mm = padZero(dt.getMinutes())
    14. //秒
    15. const ss = padZero(dt.getMilliseconds())
    16. return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
    17. //`YYYY-MM-DD HH:mm:ss`
    18. }
    19. //添加补0函数
    20. function padZero(n){
    21. return n>9?n:'0'+n
    22. }
    23. //向外暴露供外界使用
    24. module.exports = {
    25. dateFormat
    26. }

    test

    1. //导入自定义格式化时间模块
    2. const time = require('./17.dateformat')
    3. //调用方法进行时间的格式化
    4. const dt = new Date()
    5. //输出
    6. const newDt = time.dateFormat(dt)
    7. console.log(newDt)

    2.使用moment对时间进行格式化

    1. //1.导入moment包
    2. const moment = require('moment')
    3. const dt = moment().format('YYYY-MM-DD HH:mm:ss')
    4. console.log(dt)

    五、案例 实现clock时钟的web服务器

    文件目录:

     

     

     clock.html

    1. html>
    2. <html>
    3. <head>
    4. <meta charset="UTF-8">
    5. <link rel='stylesheet' href='./clock.css' />
    6. <title>时钟title>
    7. head>
    8. <body>
    9. <div class="clock" id="clock">
    10. <div class="origin">div>
    11. <div class="clock-line hour-line" id="hour-line">div>
    12. <div class="clock-line minute-line" id="minute-line">div>
    13. <div class="clock-line second-line" id="second-line">div>
    14. <div class="date-info" id="date-info">div>
    15. <div class="time-info" >
    16. <div class="time" id="hour-time">div>
    17. <div class="time" id="minute-time">div>
    18. <div class="time" id="second-time">div>
    19. div>
    20. div>
    21. <script type='text/javascript' src='./clock.js'>script>
    22. body>
    23. html>

    clock.css

    1. *{
    2. margin:0;
    3. padding:0;
    4. }
    5. /* 外面的大盒子 */
    6. .clock{
    7. width:400px;
    8. height:400px;
    9. border:10px solid #333;
    10. box-shadow: 0px 0px 20px 3px #444 inset;
    11. border-radius:50%;
    12. position:relative;
    13. margin:5px auto;
    14. z-index:10;
    15. background-color:#f6f6f6;
    16. }
    17. /* 时钟数字 */
    18. .clock-num{
    19. width:40px;
    20. height:40px;
    21. font-size:22px;
    22. text-align:center;
    23. line-height:40px;
    24. position:absolute;
    25. z-index:8;
    26. color:#555;
    27. font-family:fantasy, 'Trebuchet MS';
    28. }
    29. .em_num{
    30. font-size:28px;
    31. }
    32. /* 指针 */
    33. .clock-line{
    34. position:absolute;
    35. z-index:20;
    36. }
    37. .hour-line{width:100px;
    38. height:4px;
    39. top:198px;
    40. left:200px;
    41. background-color:#000;
    42. border-radius:2px;
    43. transform-origin:0 50%;
    44. box-shadow:1px -3px 8px 3px #aaa;
    45. }
    46. .minute-line{
    47. width:130px;
    48. height:2px;
    49. top:199px;
    50. left:190px;
    51. background-color:#000;
    52. transform-origin:7.692% 50%;
    53. box-shadow:1px -3px 8px 1px #aaa;
    54. }
    55. .second-line{
    56. width:170px;
    57. height:1px;
    58. top:199.5px;
    59. left:180px;
    60. background-color:#f60;
    61. transform-origin:11.765% 50%;
    62. box-shadow:1px -3px 7px 1px #bbb;
    63. }
    64. /* 原点 */
    65. .origin{
    66. width:20px;
    67. height:20px;
    68. border-radius:10px;
    69. background-color:#000;
    70. position:absolute;
    71. top:190px;
    72. left:190px;
    73. z-index:14;
    74. }
    75. /* 日期 时间 */
    76. .date-info{
    77. width:160px;
    78. height:28px;
    79. line-height:28px;
    80. text-align:center;
    81. position:absolute;
    82. top:230px;
    83. left:120px;
    84. z-index:11;
    85. color:#555;
    86. font-weight:bold;
    87. font-family:'微软雅黑';
    88. }
    89. .time-info{
    90. width:92px;
    91. height:30px;
    92. line-height:30px;
    93. text-align:center;
    94. position:absolute;
    95. top:270px;
    96. left:154px;
    97. z-index:11;
    98. background-color:#555;
    99. padding:0;
    100. box-shadow:0px 0px 9px 2px #222 inset;
    101. }
    102. .time{
    103. width:30px;
    104. height:30px;
    105. text-align:center;
    106. float:left;
    107. color:#fff;
    108. font-weight:bold;
    109. }
    110. #minute-time{
    111. border-left:1px solid #fff;
    112. border-right:1px solid #fff;
    113. }
    114. /* 刻度 */
    115. .clock-scale{
    116. width:195px;
    117. height:2px;
    118. transform-origin:0% 50%;
    119. z-index:7;
    120. position:absolute;
    121. top:199px;
    122. left:200px;
    123. }
    124. .scale-show{
    125. width:12px;
    126. height:2px;
    127. background-color:#555;
    128. float:left;
    129. }
    130. .scale-hidden{
    131. width:183px;
    132. height:2px;
    133. float:left;
    134. }

     clock.js

    1. (function(){//自己调用自己
    2. //页面加载完成时运行,将实参传给下面的函数
    3. window.onload=initNumXY(200, 160, 40,40);
    4. //获取指针的时分秒
    5. var hour_line = document.getElementById("hour-line");
    6. var minute_line = document.getElementById("minute-line");
    7. var second_line = document.getElementById("second-line");
    8. var date_info = document.getElementById("date-info");
    9. var week_day = [
    10. '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'
    11. ];
    12. //获取时间的时分秒
    13. var hour_time = document.getElementById("hour-time");
    14. var minute_time = document.getElementById("minute-time");
    15. var second_time = document.getElementById("second-time");
    16. //在底部调用函数
    17. function setTime(){
    18. var this_day = new Date();
    19. //如果时间大于12小时,就减去12小时
    20. var hour = (this_day.getHours() >= 12) ?
    21. (this_day.getHours() - 12) : this_day.getHours();
    22. var minute = this_day.getMinutes();
    23. var second = this_day.getSeconds();
    24. //定义小时转的角度
    25. var hour_rotate = (hour*30-90) + (Math.floor(minute / 12) * 6);
    26. //获取4位数的年份
    27. var year = this_day.getFullYear();
    28. //获取月份,如果小于10,要加0
    29. var month = ((this_day.getMonth() + 1) < 10 ) ?
    30. "0"+(this_day.getMonth() + 1) : (this_day.getMonth() + 1);
    31. //获取天数,小于10 加上0
    32. var date = (this_day.getDate() < 10 ) ?
    33. "0"+this_day.getDate() : this_day.getDate();
    34. //获取星期
    35. var day = this_day.getDay();
    36. //获取要转的度数
    37. hour_line.style.transform = 'rotate(' + hour_rotate + 'deg)';
    38. minute_line.style.transform = 'rotate(' + (minute*6 - 90) + 'deg)';
    39. second_line.style.transform = 'rotate(' + (second*6 - 90)+'deg)';
    40. //写入年月日
    41. date_info.innerHTML =
    42. year + "-" + month + "-" + date + " " + week_day[day];
    43. //在框框内写入时分秒
    44. hour_time.innerHTML = (this_day.getHours() < 10) ?
    45. "0" + this_day.getHours() : this_day.getHours();
    46. minute_time.innerHTML = (this_day.getMinutes() < 10) ?
    47. "0" + this_day.getMinutes() : this_day.getMinutes();
    48. second_time.innerHTML = (this_day.getSeconds() < 10) ?
    49. "0" + this_day.getSeconds():this_day.getSeconds();
    50. }
    51. //1秒执行一次
    52. setInterval(setTime, 1000);
    53. //让1至12个数按函数排这个位置
    54. function initNumXY(R, r, w, h){
    55. //数组里面装对象,每个元素对应每个数字的位置
    56. var numXY = [
    57. {
    58. "left" : R + 0.5 * r - 0.5 * w,
    59. "top" : R - 0.5 * r * 1.73205 - 0.5 * h
    60. },
    61. {
    62. "left" : R + 0.5 * r * 1.73205 - 0.5 * w,
    63. "top" : R - 0.5 * r - 0.5 * h
    64. },
    65. {
    66. "left" : R + r - 0.5 * w,
    67. "top" : R - 0.5 * h
    68. },
    69. {
    70. "left" : R + 0.5 * r * 1.73205 - 0.5 * w,
    71. "top" : R + 0.5 * r - 0.5 * h
    72. },
    73. {
    74. "left" : R + 0.5 * r - 0.5 * w,
    75. "top" : R + 0.5 * r * 1.732 - 0.5 * h
    76. },
    77. {
    78. "left" : R - 0.5 * w,
    79. "top" : R + r - 0.5 * h
    80. },
    81. {
    82. "left" : R - 0.5 * r - 0.5 * w,
    83. "top" : R + 0.5 * r * 1.732 - 0.5 * h
    84. },
    85. {
    86. "left" : R - 0.5 * r * 1.73205 - 0.5 * w,
    87. "top" : R + 0.5 * r - 0.5 * h
    88. },
    89. {
    90. "left" : R - r - 0.5 * w,
    91. "top" : R - 0.5 * h
    92. },
    93. {
    94. "left" : R - 0.5 * r * 1.73205 - 0.5 * w,
    95. "top" : R - 0.5 * r - 0.5 * h
    96. },
    97. {
    98. "left" : R - 0.5 * r - 0.5 * w,
    99. "top": R - 0.5 * r * 1.73205 - 0.5 * h
    100. },
    101. {
    102. "left" : R - 0.5 * w,
    103. "top" : R - r - 0.5 * h
    104. }
    105. ];
    106. //获取大盒子
    107. var clock = document.getElementById("clock");
    108. //for循环,规定值小于12,
    109. for(var i = 1; i <= 12; i++){
    110. //如果除以3能除完,就在div盒子里面写入,并且有两个样式
    111. if(i%3 == 0) {
    112. clock.innerHTML += "
      "+i+"
      "
      ;
    113. } else {
    114. clock.innerHTML += "
      " + i + "
      "
      ;
    115. }
    116. }
    117. //获取时钟数字的class类名
    118. var clock_num = document.getElementsByClassName("clock-num");
    119. //时钟数的位置
    120. for(var i = 0; i < clock_num.length; i++) {
    121. clock_num[i].style.left = numXY[i].left + 'px';
    122. clock_num[i].style.top = numXY[i].top + 'px';
    123. }
    124. //在div盒子里面写入刻度
    125. for(var i = 0; i < 60; i++) {
    126. clock.innerHTML += "
      " +
    127. "
      "
      +
    128. "
      "
      +
    129. "
      ";
  • }
  • var scale = document.getElementsByClassName("clock-scale");
  • //将刻度分散布在整个钟表上
  • for(var i = 0; i < scale.length; i++) {
  • scale[i].style.transform="rotate(" + (i * 6 - 90) + "deg)";
  • }
  • }
  • })();
  • nodejs代码

    1. //1.导入node模块
    2. //导入http模块
    3. const http = require('http')
    4. //导入fs文件系统模块
    5. const fs = require('fs')
    6. //导入path路径处理模块
    7. const path = require('path')
    8. //2.创建web服务器
    9. //创建服务器实例化对象
    10. const server = http.createServer()
    11. //监听服务器的request事件
    12. server.on('request',(req,res)=>{
    13. //获取客户端请求的url地址
    14. const url = req.url
    15. //把获取的url地址映射成具体文件的存放路径
    16. //const fpath = path.join(__dirname,url)
    17. //优化路径
    18. //定义空白的路径
    19. let fpath = ''
    20. if(url === '/'){
    21. fpath = path.join(__dirname,'./clock/clock.html')
    22. }else{
    23. fpath = path.join(__dirname,'/clock',url)
    24. }
    25. //根据映射过来的文件路径读取文件
    26. fs.readFile(fpath,'utf8',(err,dataStr)=>{
    27. //读取文件失败,向客户端响应错误信息
    28. if(err){return res.end('404 NOT FOUND')}
    29. //读取文件成功,将读取成功的内容响应给客户端
    30. res.end(dataStr)
    31. })
    32. })
    33. //启动服务器
    34. server.listen(8080,()=>{
    35. console.log('server running at http://127.0.0.1:8080')
    36. })

    实现效果:

     

     

  • 相关阅读:
    软件测试--selenium安装使用
    在 Python 中使用 Selenium 从下拉菜单中选择选项
    C语言-基础
    树大总结(王道+红皮书)
    PostgreSQL查询表操作
    学习响应式布局
    联合投稿其乐融融 抖音共创助你大显身手
    美国Embarcadero公司正式发布2023 RAD Studio Delphi C++ Builder 12 Athens
    端子排延时中间继电器DZS-822/DC110V
    python3 获取 进程id 线程id
  • 原文地址:https://blog.csdn.net/m0_46420244/article/details/127926117