今天踩了一个小坑
今天我要将一个html页面的内容发到客户端去,我觉得这么写完全没问题啊,怎么就是没数据返回呢?
http.createServer((req,res) => {
fs.readFile('./login.html',(err, data) => {
res.write(data)
})
res.end()
})
我试了好多遍,吧res.end()
和res.write()
换了好多个地方,就是不知道为什么不行,现在明白了,把我的理解写一下
-
fs.readFile()是一个异步读取文件的方法,当第一个参数是一个路径时,其底层其实是调用了
fs.open()
、fs.read()
、fs.close()
这些方法的,所以说当函数调用结束,数据流就被关闭了 -
response.write()的一个小特性
When write function is called with empty string or buffer, it does nothing and waits for more input.
意思是说,“当使用空字符串或缓冲区调用write函数时,它什么也不做,而是等待更多的输入。 ”
http.createServer((req,res) => {
fs.readFile('./login.html',(err, data) => {
res.write(data) // 这里的data在了缓冲区内,所以实际上它啥也不干
})
// fs.readFile() 方法调用完成,读取流被关闭了,缓冲区被清空了
res.end() // 之前的res.write()根本没点屁用,所以这里一点数据都返回不了
})
所以就只能这样写
http.createServer((req,res) => {
fs.readFile('./login.html',(err, data) => {
res.write(data)
res.end() // 这样写在数据流未关闭时将数据完整发送出去了
})
})
结论:在fs.readFile
的 回调函数中使用 red.write()
时,必须在 fs.readFile
的回调函数中使用res.end()