动态读取目录readdir(),可遍历生成数组。
const fs = require('fs')
fs.readdir('./data/views/source', (err, files) => {
if (err) {
console.log('目录不存在')
} else {
console.log(files)
}
})
动态读取目录demo2
const http = require('http')
const fs = require('fs')
const server = http.createServer()
const wwwDir = 'C:/Users/asus/Desktop/前端学习/其余/Node/www'
server.on('request', (req, res) => {
let url = req.url
let filePath = '/index.html'
if (url !== '/') {
filePath = url
}
fs.readFile(`${wwwDir}${filePath}`, (err, data) => {
if (err) {
return res.end('404 Not Found')
}
fs.readdir(wwwDir, (err, files) => {
if (err) {
return res.end('can not find www dir')
}
console.log(files)
})
res.end(data)
})
})
server.listen(8080, () => {
console.log('Server is running at http://127.0.0.1:8080')
})
服务启动后,我们可以手动新建一个目录,然后刷新页面,就发现我们新增的目录了。
读取字符串模板
const http = require('http')
const fs = require('fs')
const server = http.createServer()
const wwwDir = 'C:/Users/asus/Desktop/前端学习/其余/Node/www'
server.on('request', (req, res) => {
let url = req.url
let filePath = '/index.html'
if (url !== '/') {
filePath = url
}
fs.readFile(`${wwwDir}${filePath}`, (err, data) => {
if (err) {
return res.end('404 Not Found')
}
fs.readdir(wwwDir, (err, files) => {
if (err) {
return res.end('can not find www dir')
}
console.log(files)
})
data = data.toString()
console.log(data)
res.end(data)
})
})
server.listen(8080, () => {
console.log('Server is running at http://127.0.0.1:8080')
})
通过data = data.toString()方法
const http = require('http')
const fs = require('fs')
const server = http.createServer()
const wwwDir = 'C:/Users/asus/Desktop/前端学习/其余/Node/www'
server.on('request', (req, res) => {
let url = req.url
let filePath = '/index.html'
if (url !== '/') {
filePath = url
}
fs.readFile(`${wwwDir}${filePath}`, (err, data) => {
if (err) {
return res.end('404 Not Found')
}
fs.readdir(wwwDir, (err, files) => {
if (err) {
return res.end('can not find www dir')
}
let content = ''
files.forEach(item => {
content += `
<button>你好!${item}</button>
`
})
data = data.toString()
console.log(content)
res.end(data)
})
})
})
server.listen(8080, () => {
console.log('Server is running at http://127.0.0.1:8080')
})
网友评论