Node.js: Three ways to write a file

  • 2021-01-25 07:07:49
  • OfStack

This article to share the Node. js write file three ways, specific content and are as follows

1. Write files through a pipeline stream
The use of pipeline transmission of 2-base stream, can achieve automatic management of the stream, the Writable stream do not have to be careful of the Readable stream stream too fast and collapse, suitable for large and small file transfer (recommended)


var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname)); //  Must be decoded url
 readStream.pipe(res); //  Pipeline transport 
 res.writeHead(200,{
   'Content-Type' : contType
 });

 //  Error handling 
 readStream.on('error', function() {
   res.writeHead(404,'can not find this page',{
     'Content-Type' : 'text/html'
   });
   readStream.pause();
   res.end('404 can not find this page');
   console.log('error in writing or reading ');
 });

2. Manually manage stream writes
Manually manage the flow, suitable for the size of the file processing


var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname));
 res.writeHead(200,{
   'Content-Type' : contType
 });

 //  Fires the function when there is data to read, chunk Is the block read 
 readStream.on('data',function(chunk) {
   res.write(chunk);
 });

 //  Handling of errors 
 readStream.on('error', function() {
   res.writeHead(404,'can not find this page',{
     'Content-Type' : 'text/html'
   });
   readStream.pause();
   res.end('404 can not find this page');
   console.log('error in writing or reading ');
 });

 //  Data read finished 
 readStream.on('end',function() {
   res.end();
 });

3, through the first reading data write
Read all the contents of the file in one time, suitable for small files (not recommended)


fs.readFile(decodeURIComponent(root + filepath.pathname), function(err, data) {
   if(err) {
     res.writeHead(404,'can not find this page',{
       'Content-Type' : 'text/html'
     });
     res.write('404 can not find this page');

   }else {
     res.writeHead(200,{
       'Content-Type' : contType
     });
     res.write(data);
   }
   res.end();
 });

The above is all the content of this article, I hope to help you learn.


Related articles: