gpt4 book ai didi

node.js - 在 Node.js 中读取文件

转载 作者:IT老高 更新时间:2023-10-28 21:46:16 29 4
gpt4 key购买 nike

我对在 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 与试图打开和读取它的文件位于同一目录中。

但是,在控制台中我得到:

{ [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 - 在 Node.js 中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18386361/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com