Node.js | 青训营笔记

70 阅读2分钟

Node.js 学习笔记

这是我参与「第五届青训营 」笔记创作活动的第5天,入门node.js。

一、认识Node.js

Node.js是一个能够在服务器端运行JavaScript的开放源代码、跨平台JavaScript运行环境。下面用一个经典例子来认识一下

import http  from "http";   //采用ES模块化规范

const hostname = 'localhost';
const port = 8000;

const server = http.createServer((req, res) => {
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

1675424269109.png

其主要模块有文件系统的I/O、网络(HTTP、TCP、UDP、DNS、TLS/SSL等)、数据流等等;其用途可包括:

  • Web服务API,比如RESTFUL
  • 实时多人游戏
  • 后端的Web服务,例如跨域、服务器端的请求
  • 多客户端的通信,如即时通信

二、核心API介绍及实践:

1、文件系统fs

我们可以通过fs对文件进行读取,写入,下面实现一个例子:

import fs from "fs";

fs.readFile("./test.txt",function (err,data) {  // readFile是异步的,readFileSync是同步的
  if(err){
    return console.log(err);
  }
  console.log('文件中的内容', data.toString());
})

fs.writeFile("./input.txt",'hello node.js',function (err) {
  if(err){
    return console.log(err);
  }
  console.log("写入成功!!!");
})

image.png

文件系统的I/O功能可以说是每个系统的“必经之路”,以上仅仅展示了异步的读取与写入,其他还有很多有趣的方法,小伙伴可以下去了解~。

2、网络http

在了解了文件系统之后,后台的交互还要通过网络请求来获取数据以及展示。下面就用一个简单的例子展示http。

// 这是一个获取路劲中参数的例子
// url: http://127.0.0.1:3000/?name=%22rhs%22
import http from "http";
import urlLib from "url";

const hostname = '127.0.0.1';
const port = 3000;

const serve = http.createServer(function (req,res) {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  let obj=urlLib.parse(req.url, true);
  let url=obj.pathname;
  let GET={};
  GET=obj.query;
  console.log(url,GET);
  res.write('aaaaa');
  res.end();
})

serve.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
})

三、课后个人总结:

在前端领域中,学好node.js不仅可以自己获取数据,操作数据,还可以将后端同学提供的API进行重新组织(BFF)。