节点:如何读取文件
Node: How to read file?
我想读取一个文件,并返回作为对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!
当我加载页面localhost:5000
时,页面旋转,什么都没有发生,我在这里做什么不正确
我是Node的新手。
您使用的是readFile
方法的同步版本。如果这是你想要的,不要给它回叫。它返回一个字符串(如果您通过编码):
app.get('/', function (request, response) {
response.send(fs.readFileSync('./index.html', 'utf8'));
});
或者(通常更合适),您可以使用异步方法(并取消编码,因为您似乎期望Buffer
):
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
});
});
相关文章:
- 使用JS/NodeJS测试并读取文件中的变量
- 当读取文件时,浏览器打开良好,但它是空白浏览器
- 当尝试使用ajax读取文件时,变量返回undefined
- 用一些像jsBin/jsFiddle/codePen这样的工具读取文件
- 在Windows Metro风格的Javascript应用程序中读取文件内容
- 咕噜声.js无法读取文件(错误代码:EISDIR)
- 如何从文件夹中读取文件
- Javascript - 如何读取文件
- 如何从 Duktape 中运行的 JavaScript 代码中读取文件
- 当客户端是服务器时,使用 client-JS 读取文件结构
- 如何从chrome扩展名读取文件
- 为什么“;readFile”;使用比读取文件更多的内存's的内容长度
- 在html中读取文件
- 使用javascript读取文件
- 节点尝试在同步写入完成之前读取文件
- 无法通过FileReader读取文件
- 从php中的本地磁盘读取文件
- 使用Javascript读取文件
- 是否可以使用 javascript 从目录中读取文件
- 通过网络浏览器从 URL javascript 读取文件