Home >Web Front-end >JS Tutorial >Let's briefly talk about streams in Node.js and talk about three ways to read files

Let's briefly talk about streams in Node.js and talk about three ways to read files

青灯夜游
青灯夜游forward
2021-08-20 10:17:202822browse

This article will give you a brief understanding of the streams in Node.js, and introduce the three ways to read files: asynchronous reading of files, synchronous reading of files and streaming of reading files. .

Let's briefly talk about streams in Node.js and talk about three ways to read files

Learn some basics of Node.js

1.fs module built-in module

npm i    第三方模块

Custom module written by myself (write js file). [Recommended learning: "nodejs Tutorial"]

2. Read the file

  • Asynchronously read the file (readFile )

To solve the problem, use promise

  • ##Read the file synchronously

    readFileSync

  • var nr = fs.readFileSync('./b.txt', 'utf-8')
    console.log(nr)
  • Read the file by stream

Read the video file and display the progress by percentage readVideo.js

Copy small files first read and then copy copyFile.js

  • Write data

    ① Asynchronously write data

Copy big file

copybigFile.js

3. http Module

Method:

Create a service:

createServer((req,res)=>{
  // 设置一个响应头 : 
  res.writeHead(200, {"Content-Type":"text/html;charset=utf-8"});
  req.url  // 获取客户端请求的网址  (除了 协议 端口 域名 之外的地址  http://www.baidu.com?main=22&pid=90)
  res.write(); // 响应用户的请求
  res.end(); // 结束响应
})
    get("url路径", 回调方法)  // 方法  请求服务器数据

  • showPage.js
Exercise questions:

  • ['1',',',',','2','3','9',',',','] Move the comma to the right

  • ② There is an array with 1000 elements. The stored numbers are 1-999. One number is repeated. Please find it out.

For more programming-related knowledge, please Visit:

Programming Video! !

The above is the detailed content of Let's briefly talk about streams in Node.js and talk about three ways to read files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete