读取目录中的所有文件,将它们存储在对象中,然后发送对象 [英] Reading all files in a directory, store them in objects, and send the object
问题描述
我不知道这是否可行,但是可以了.而且使用回调会更加困难.
I do not know if this is possible, but here goes. And working with callbacks makes it even more difficult.
我有一个目录,其中包含html文件,这些文件要通过node.js和socket.io的对象块形式发送回客户端.
I have a directory with html files that I want to send back to the client in Object chunks with node.js and socket.io.
我所有的文件都在/tmpl
All my files are in /tmpl
因此套接字需要读取/tmpl中的所有文件.
So socket needs to read all the files in /tmpl.
对于每个文件,它必须将数据存储在一个对象中,该对象以文件名作为键,将内容作为值.
for each file it has to store the data in an object with the filename as the key, and the content as the value.
var data;
// this is wrong because it has to loop trough all files.
fs.readFile(__dirname + '/tmpl/filename.html', 'utf8', function(err, html){
if(err) throw err;
//filename must be without .html at the end
data['filename'] = html;
});
socket.emit('init', {data: data});
最后的回调也是错误的.当目录中的所有文件都完成后,必须调用它.
The final callback is also wrong. It has to be called when all the files in the directory are done.
但是我不知道如何创建代码,有人知道这是否是possibel吗?
But I do not know how to create the code, anyone know if this is possibel?
推荐答案
因此,分为三个部分.读取,存储和发送.
So, there are three parts. Reading, storing and sending.
这是阅读部分:
var fs = require('fs');
function readFiles(dirname, onFileContent, onError) {
fs.readdir(dirname, function(err, filenames) {
if (err) {
onError(err);
return;
}
filenames.forEach(function(filename) {
fs.readFile(dirname + filename, 'utf-8', function(err, content) {
if (err) {
onError(err);
return;
}
onFileContent(filename, content);
});
});
});
}
这是存储部分:
var data = {};
readFiles('dirname/', function(filename, content) {
data[filename] = content;
}, function(err) {
throw err;
});
发送部分取决于您.您可能希望一一发送或阅读完毕后发送给他们.
The sending part is up to you. You may want to send them one by one or after reading completion.
如果要在读取完成后发送文件,则应使用fs
函数的同步版本或使用Promise.异步回调不是一种好的样式.
If you want to send files after reading completion you should either use sync versions of fs
functions or use promises. Async callbacks is not a good style.
您还询问了如何剥离扩展程序.您应该一个一个地处理问题.没有人会为您编写完整的解决方案.
Additionally you asked about stripping an extension. You should proceed with questions one by one. Nobody will write a complete solution just for you.
这篇关于读取目录中的所有文件,将它们存储在对象中,然后发送对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!