Home > Web Front-end > JS Tutorial > body text

Three ways to write files in Node.js_node.js

WBOY
Release: 2016-05-16 15:11:29
Original
1541 people have browsed it

This article shares three ways to write files in Node.js. The specific content is as follows

1. Write files through pipe flow
Using pipes to transmit binary streams can automatically manage streams. Writable streams don’t have to worry about readable streams crashing too fast. Suitable for large and small file transfers (recommended)

var readStream = fs.createReadStream(decodeURIComponent(root + filepath.pathname)); // 必须解码url
 readStream.pipe(res); // 管道传输
 res.writeHead(200,{
   'Content-Type' : contType
 });

 // 出错处理
 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 ');
 });

Copy after login

2. Manually manage stream writing
Manual management flow, suitable for processing large and small files

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

 // 当有数据可读时,触发该函数,chunk为所读取到的块
 readStream.on('data',function(chunk) {
   res.write(chunk);
 });

 // 出错时的处理
 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 ');
 });

 // 数据读取完毕
 readStream.on('end',function() {
   res.end();
 });

Copy after login

3. Read and write data in one go
Read all the contents of the file at once, 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();
 });
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template