Three file writing methods for Node. js and three write methods for node. js
This article describes three methods for writing files in Node. js.
1. Write files through the pipeline stream
Using pipelines to transmit binary streams can achieve automatic stream management. Writing streams do not have to worry about the excessive speed of readable streams and crash. This is suitable for transferring large and small files (recommended)
Var readStream = fs. createReadStream (decodeURIComponent (root + filepath. pathname); // The url readStream must be decoded. pipe (res); // pipeline transfers 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 ('2014 can not find this page'); console. log ('error in writing or reading ');});
2. Manually manage stream writing
Manual stream management, suitable for processing large and small files
Var readStream = fs. createReadStream (decodeURIComponent (root + filepath. pathname); res. writeHead (200, {'content-type': contType}); // This function is triggered when data is readable. The chunk is the read block readStream. on ('data', function (chunk) {res. write (chunk) ;}); // process readStream when an error occurs. on ('error', function () {res. writeHead (404, 'can not find this page', {'content-type': 'text/html'}); readStream. pause (); res. end ('2014 can not find this page'); console. log ('error in writing or reading');}); // readStream after data is read. on ('end', function () {res. end ();});
3. Write Data through one-time reading
Read all the content of the file at a 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, hoping to help you learn.
Articles you may be interested in:
- Use JSP to write and upload files
- Compile File Upload Using jsp
- C # Summary of methods for reading and writing files
- Efficiency Comparison Between Reading and Writing files and reading and writing databases in php
- Php concurrent read/write file conflict solution
- Php multi-user file read/write conflict solution
- Examples of multiple methods for creating folders for Java read/write files
- Python read/Write File Operation example Program
- C ++ read/write file stream instance program description