What is this problem? There’s nothing wrong with it

  node.js, question



1. The direct bug was said by the students on the first floor.
2. But you didn’t use streaming when reading files, so I think you can use it directly._this.res.end(data)Can avoid your problem
3. Read out some comments from your code for you

  • fs.exists(path, callback)This method has been used for a long time.Deprecated, so also do not recommend you to use, usefs.lstat() or fs.access()Replace it!

  • Since you want to use write, you can read the file by stream when reading it, so if it is a very large file, you can read it by stream. now you read the file, then write directly, and finally end, or read the contents of the file into the memory at one time. it is still a poor experience for large files. it is recommended to use the following code to try it out.

const filePath=path.join(__dirname, 'xxxx.json')
 fs.lstat(filePath, (err, stats) => {
 if(err) return res.status(500).end('file is not founded')
 res.writeHead(200, {
 'Content-Type' : 'application/json',
 const readStream = fs.createReadStream(filePath)
 readStream.on('end', () => {
 readStream.on('error', (error) => {
 res.end(`read file stream error ${error.message}`)

I wrote some casually, you can optimize, log, or use async to solve callback hell problem, etc. there are also header types, error messages returned, etc. however, the core streaming code should be no problem, only for reference, hoping to be helpful to you.