node.js入门第二天

1. 复习第一天的内容
  • 基本概念:复习 Node.js 的特点和用途,了解其非阻塞 I/O 模型。
  • 环境搭建:确保你已经成功安装 Node.js,并能够在命令行中运行 nodenpm
2. 理解模块系统
  • CommonJS 模块:学习如何使用 requiremodule.exports

    • 创建一个模块(例如 math.js):

      // math.js
      function add(a, b) {
          return a + b;
      }
      
      module.exports = {
          add
      };
      

    • 在另一个文件中引入模块:

      // app.js
      const math = require('./math');
      console.log(math.add(5, 3)); // 输出 8
      

  • ES6 模块(如果你的 Node.js 版本支持):

    • 使用 importexport

      // math.mjs
      export function add(a, b) {
          return a + b;
      }
      

    • 在另一个文件中引入:

      // app.mjs
      import { add } from './math.mjs';
      console.log(add(5, 3)); // 输出 8
      
3. 文件系统操作
  • 学习如何使用 Node.js 的 fs 模块进行文件操作。
    • 读取文件

      const fs = require('fs');
      
      fs.readFile('example.txt', 'utf8', (err, data) => {
          if (err) {
              console.error(err);
              return;
          }
          console.log(data);
      });
      
    • 写入文件

      fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
          if (err) {
              console.error(err);
              return;
          }
          console.log('File has been written');
      });
      

4. 创建简单的 HTTP 服务器
  • 学习如何使用 Node.js 创建一个基本的 HTTP 服务器。
    const http = require('http');
    
    const server = http.createServer((req, res) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Hello, World!\n');
    });
    
    server.listen(3000, () => {
        console.log('Server running at http://localhost:3000/');
    });
    
5. 理解异步编程
  • 回调函数:理解如何使用回调函数处理异步操作。

  • Promise:学习如何使用 Promise 处理异步操作。

    const fs = require('fs').promises;
    
    fs.readFile('example.txt', 'utf8')
        .then(data => {
            console.log(data);
        })
        .catch(err => {
            console.error(err);
        });
    

  • async/await:学习如何使用 async/await 语法简化异步代码。

    async function readFile() {
        try {
            const data = await fs.readFile('example.txt', 'utf8');
            console.log(data);
        } catch (err) {
            console.error(err);
        }
    }
    
    readFile();
    
6. 实践练习
  • 创建一个简单的 HTTP 服务器,响应不同的 URL 请求。
  • 尝试读取和写入文件,记录一些数据。
  • 使用 Promise 和 async/await 处理文件操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值