This article shares three ways of node.js writing, specific content and the following
1, flow through the pipeline to write files
The use of pipeline transmission of binary flow, can realize automatic management flow, writable flow does not have to be careful of the readable flow of the fast and crash, suitable for size file transfer (recommended)
var readstream = Fs.createreadstream (decodeuricomponent (root + filepath.pathname)); URL
readstream.pipe (res) must be decoded;//Pipeline Transmission
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
Manual management of the flow, suitable for size file processing
var readstream = Fs.createreadstream (decodeuricomponent (root + filepath.pathname));
Res.writehead (200,{
' content-type ': Conttype
});
When the data is readable, the function is triggered, chunk the block
readstream.on (' Data ', function (chunk) {
res.write (chunk);}) as read
;
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 ');
});
Data read
Readstream.on (' End ', function () {
res.end ();
});
3, through a one-time read data write
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 to help you learn.