Javascript 节点:如何读取文件?
我想读取一个文件并返回作为对Javascript 节点:如何读取文件?,javascript,node.js,Javascript,Node.js,我想读取一个文件并返回作为对GET请求的响应 这就是我正在做的 app.get('/', function (request, response) { fs.readFileSync('./index.html', 'utf8', function (err, data) { if (err) { return 'some issue on reading file'; } var buffer = new Buff
GET
请求的响应
这就是我正在做的
app.get('/', function (request, response) {
fs.readFileSync('./index.html', 'utf8', function (err, data) {
if (err) {
return 'some issue on reading file';
}
var buffer = new Buffer(data, 'utf8');
console.log(buffer.toString());
response.send(buffer.toString());
});
});
index.html
hello world!
当我加载pagelocalhost:5000
时,页面旋转,什么也没有发生,我在这里做什么不正确
我是Node的新手。您使用的是同步版本的。如果这是你想要的,不要给它回叫。它返回一个字符串(如果传递编码):
或者(通常更合适)您可以使用异步方法(并且摆脱编码,因为您似乎希望使用缓冲区
):
您正在使用的是的同步版本。如果这是你想要的,不要给它回叫。它返回一个字符串(如果传递编码):
或者(通常更合适)您可以使用异步方法(并且摆脱编码,因为您似乎希望使用缓冲区
):
其余的应用程序/服务器配置是什么样子的?您是否看到任何控制台输出?其余的应用程序/服务器配置是什么样子的?您是否看到任何控制台输出?
app.get('/', function (request, response) {
response.send(fs.readFileSync('./index.html', 'utf8'));
});
app.get('/', function (request, response) {
fs.readFile('./index.html', { encoding: 'utf8' }, function (err, data) {
// In here, `data` is a string containing the contents of the file
});
});