我对在 Node.js 中读取文件感到很困惑。
fs.open('./start.html', 'r', function(err, fileToRead){
if (!err){
fs.readFile(fileToRead, {encoding: 'utf-8'}, function(err,data){
if (!err){
console.log('received data: ' + data);
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
}else{
console.log(err);
}
});
}else{
console.log(err);
}
});
文件 start.html
与试图打开和读取它的文件位于同一目录中。
但是,在控制台中我得到:
{ [错误:ENOENT,打开’./start.html’] errno:34,代码:’ENOENT’,路径:’./start.html’}
有任何想法吗?
原文由 Eugene Kostrikov 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
path.join(__dirname, '/start.html')
;感谢 dc5。