A sentence in response was found in the process of reading node API
The response inherits from Stream, and additionally implements the following:
This class implements (rather than inherits from) the writable stream interface. It is an [EventEmitter] with the following events 🙂
-
Fs.createreadstream (filePath).pipe(response);
- CreateReadStrem is returned:
See readable Streams.
- A response is of course a response
- Pipe is the connection of two data streams.
- CreateReadStrem is returned:
-
Does that output the data stream?
- We know that WriteStream (a writable stream is an abstraction of the destination to which data is to be written.)
- All examples of Writable streams (including the fs write-in stream) implement the interface defined by the stream.Writable class.
- That is, you can output streams of data
- And the preface mentioned that Response also implements a writable stream interface
- Fs.createreadstream then concatenates the response with response and is ready to output
-
Here’s a quick example
const http = require('http'); const fs = require('fs'); const url = require('url'); const path =require('path'); // Get the root directory from the command line argument. The default is the current directory: var root = path.resolve(process.argv[2] | |'. '); console.log('Static root dir: ' + root); // Create server: var server = http.createServer(function (request, response) { // Get the path of the URL, like '/ CSS /bootstrap.css': var pathname = url.parse(request.url).pathname; / / get the corresponding local file path, like '/ SRV/WWW/CSS/bootstrap CSS' : var filepath = path.join(root, pathname); Stat () to check whether a file exists.Stats is the fs.stats object, which provides information about a file fs.stat(filepath, function (err, stats) { if(! err && stats.isFile()) {Stats.isfile () returns true if the fs.stats object represents a normal file // There is no error and the file exists: console.log('200' + request.url); // Send 200 responses: response.writeHead(200); // Redirect the file stream to response:Fs. CreateReadStream (filepath.) pipe (response); }else { // Error or file does not exist: console.log('404' + request.url); // Send a 404 response: response.writeHead(404); response.end('404 Not Found'); }}); }); server.listen(8080); Copy the code