node学习笔记(一)

  • 什么是node.js?

    node.js不是一种新的编程语言,仅仅只是一种后台技术,和JavaPHP.NET等可以视为平级竞争关系,本质上使用的还是JavaScript。node官网是这样介绍node.js的,node是一个基于Chrome的V8 JavaScript引擎构建的JavaScript运行时

  • 起步

    官网下载对应的安装包,建议安装长期稳定版本,我自己安装的是V10.13.0 LTS,安装教程比较简单,此处略过,请自行百度详细图文教程,安装成功后再控制台下执行node -v可会显示node版本号。

  • 核心模块

    • fs-文件系统模块(一般用于处理文件)

      创建test.txt文件,并随意添加文件内容

      同级目录下创建fs.js文件,文件内容如下:

      // 引入文件系统模块,此处遵循CommonJs规范
      const fs = require('fs');
      // 同步读取文件
      const data = fs.readFileSync('./test.txt');
      console.log('同步读取'+data);
      // 异步读取文件(推荐写法)
      fs.readFile('./test.txt',function(err,data){
          if (err) throw err;
          console.log('异步读取'+data);
      });
      // 同步读取文件
      console.log('run');
      

      以上代码包括同步和异步两种读取文件的方法,主要区别就是同步操作会阻塞进程,异步读取文件的方法上午执行不会影响后续代码的执行,同步读取文件的方法执行成功后才会执行后续的代码,所以以上代码的输出结果如下:

      同步读取nodejs核心模块
      run
      异步读取nodejs核心模块
      
    • Buffer-缓冲器模块(一般用于处理数据流)

      // Buffer创建不需要引入模块,全局模块Buffer
      // 创建Buffer
      const buf1 = Buffer.alloc(10);
      console.log(buf1);
      
      // 数组创建
      const buf2 = Buffer.from([1,2,3]);
      console.log(buf2);
      
      // 字符串创建
      const buf3  = Buffer.from('hello world中文');
      const buf4  = Buffer.from('hello world中文','ascii');
      console.log(buf3.toString());
      console.log(buf4.toString('ascii'));
      

      输出结果如下:

      <Buffer 00 00 00 00 00 00 00 00 00 00>
      <Buffer 01 02 03>
      hello world中文
      hello world-
      
    • HTTP模块

      新建index.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>index</title>
      </head>
      <body>
      <p>index页面</p>
      <!--添加用户-->
      <form action="/api/users" method="post">
          <input type="text" name="name">
          <input type="number" name="age">
          <input type="submit" value="新增用户">
      </form>
      <ul id="userList"></ul>
      <script type="text/javascript">
          let userList =  document.querySelector('#userList');
          fetch('/api/users').then(function(res){
              // console.log(res);
              // 转换为json对象
              return res.json();
          }).then(function (users) {
              // console.log(users);
              // 显示在界面中
              userList.innerHTML = users.map(function(user){
                  return '<li>'+user.name+'</li>'
              }).join('');
      
          }).catch(function (err) {
              alert('请求报错');
          });
      </script>
      </body>
      </html>
      

      同级目录下新建http.js文件,文件内容如下:

      // 导入fs,http模块
      const fs = require('fs');
      const http = require('http');
      const qs = require('querystring');
      let users = [{name: 'test1', age: 20}, {name: 'test2', age: 18}];
      const server = http.createServer((req, res) => {
          // 该回调函数在每次收到请求时调用
          // req 请求对象
          // res 响应对象
          // 使用res.writeHead()设置响应头
          const url = req.url;
          const method = req.method;
          if (url === '/' && method === 'GET') {
              fs.readFile('./index.html', function (err, data) {
                  if (err) {
                      // 错误处理
                      res.writeHead(500, {
                          'Content-Type': 'text/html'
                      });
                      res.end('500, Server Internal error');
                      return;
                  }
                  // 设置响应头
                  // Content-Type常见值:'text/html' 'application/json'
                  res.writeHead(200, {
                      'Content-Type': 'text/html'
                  });
                  // 返回页面数据
                  res.end(data);
              });
          } else if (url === '/api/users' && method === 'GET') {
              // 编写接口,返回json数据
              res.writeHead(500, {
                  'Content-Type': 'application/json'
              });
              // 返回页面数据
              res.end(JSON.stringify(users));
          } else if (url === '/api/users' && method === 'POST') {
              // 接收请求参数
              let body = [];
              req.on('data',(chunk) => {
                  body.push(chunk);
              }).on('end',()=>{
                  body = Buffer.concat(body).toString();
                  const user = qs.parse(body);
                  users.push(user);
                  res.end('success');
              });
          }
      });
      
      // 监听指定端口
      server.listen(3000);
      
      

      执行结果如下:
      在这里插入图片描述
      在这里插入图片描述
      在index界面也可成功新增数据

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值