Related articles
- P01: Node.js tutorial from a practical perspective
- P02: Basic node usage
- P03: Node built-in module PATH
- P04: Buffer for nodeAPI
- P05: Events of node built-in module
- P06: Node built-in module FS (1)
- P07: Node built-in module FS (2)
- P08: Node implements static server ~ create project
- P09: Node implements static server ~ Hello HTTP
- P10: Node implements static server ~ static file or folder reading
Now that we have a basic understanding of how Node works, let’s implement a system function that reads files or folders
Mining pit record
- Chinese output garbled characters
res.statusCode = 200 res.setHeader('Content-Type'.'text/plain') res.end('Ahh and gaha.') Copy the code
- Chinese garbled characters appear in the output
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }) Copy the code
or
res.writeHead(200, { 'Context-Type': 'text/plain' }) res.write('<head><meta charset="utf-8"/></head>') Copy the code
- File reading mode
Node allows you to read and output files in two ways
- One: Read and return as a file stream. Fast = recommended
fs.createReadStream(filePath).pipe(res) Copy the code
- Two: Reading the file in its entirety and then returning its contents together is simply a poor use of the API = slow
fs.readFile(filePath, (err, data) => { if (err) return res.end(data) }) Copy the code
Read a file or folder
- Blah, blah, code
Require (‘./config/defaultConfig’) updated to the following
Module. exports = {// hostname:'127.0.0.1', // port: 6969, // current folder root: process.cwd()}Copy the code
Const HTTP = require(const HTTP = require('http'Const chalk = require()'chalk')
const path = require('path')
const fs = require('fs'Const conf = require()'./config/defaultConfig') // Create a server instance const server = http.createserver ((rep, res) => {// Get path const filePath = path.join(conf.root, Stat (filePath, (err, stats) => {// Set public header res.writehead (200, {'Content-Type': 'text/plain; charset=utf-8' })
if(err) {// statusCode res.statuscode = 404 // the prompt text res.end(' could not be found${filePath} is 404`)
return
}
ifRes.statuscode = 200 fs.createreadStream (filePath).pipe(res)} (stats.isfile ()) {res.statusCode = 200 fs.createreadStream (filePath).pipe(res)}else if(stats.isdirectory ()) {fs.readdir(filePath, (err, files) => {if (err) return
res.statusCode = 200
res.end(files.join(', 'Listen (conf.port, conf.hostname, () => {const addr = 'http://${conf.hostname}:${conf.port}`
console.info(`server startd at ${chalk.green(addr)}`)})Copy the code
Code optimization
-
The above code has many callbacks, and the code is bloated and unreadable. Let’s use asynchrony to remove the callback for optimization
require-atomic-updates
Note the restriction esLint has on this item, for which the argument await is usedconst fs = require('fs') const promisify = require('util').promisify const stat = promisify(fs.stat) const readdir = promisify(fs.readdir) module.exports = async function(rep, res, Const awaitRes = await res awaitres. writeHead(200, {'Content-Type': 'text/plain; charset=utf-8' }) try { const stats = await stat(filePath) ifStatusCode = 200 fs.createreadStream (filePath).pipe(awaitRes)} (stats.isfile () {awaitres.statusCode = 200 fs.createreadStream (filePath).pipe(awaitRes)}else if(stats.isdirectory ()) {// If it is a folder, Const file = readdir(filePath) awaitres.statusCode = 200 awaitres.end (file.join()', ')}} catch (ex) {// Awaitres.statusCode = 404 // The prompt text awaitres.end (' is not found${filePath} is 404`) } } Copy the code
-
The app.js file is changed to
Const HTTP = require(const HTTP = require('http'Const chalk = require()'chalk') const path = require('path') const route = require('./header/route'Const conf = require()'./config/defaultConfig') // Create a server instance const server = http.createserver ((rep, res) => {// Get path const filePath = path.join(conf.root, Rep. url) route(rep, res, filePath)}) server.listen(conf.port, conf.hostname, () => { const addr = `http://${conf.hostname}:${conf.port}` console.info(`server startd at ${chalk.green(addr)}`)})Copy the code
-
So far, hash path input is implemented to read/forward/backward files or folders
close