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 '); });
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(); });
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(); });
The above is the entire content of this article, I hope it will be helpful to everyone’s study.