在Node.js中读取文件 [英] Read a file in Node.js
本文介绍了在Node.js中读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对在Node.js中读取文件感到很困惑.
I'm quite puzzled with reading files in 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
与尝试打开和读取文件的文件位于同一目录中.
File start.html
is in the same directory with file that tries to open and read it.
但是,在控制台中,我得到了:
However, in the console I get:
{[错误:ENOENT,打开'./start.html']错误号:34,代码:'ENOENT',路径:'./start.html'}
{ [Error: ENOENT, open './start.html'] errno: 34, code: 'ENOENT', path: './start.html' }
有什么想法吗?
推荐答案
使用path.join(__dirname, '/start.html')
;
var fs = require('fs'),
path = require('path'),
filePath = path.join(__dirname, 'start.html');
fs.readFile(filePath, {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);
}
});
感谢dc5.
这篇关于在Node.js中读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文