This article mainly introduces three types of nodes. js file writing methods, interested friends can refer to this article to share Node. three methods for writing files in js are as follows:
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.