I'm somewhat new to node, and so far I love it, but maybe I'm running into a case of it being a hammer when I need a wrench.
I've got a bunch of data in text files, and I need to load these files into a database - very simple in a normal imperative language. I want to write idiomatic node for this, so would rather use async fs calls (fs.readdir
and fs.readFile
rather than fs.readdirSync
and fs.readFileSync
). However, how do I know when all of those operations are done, so then (and only then) it's safe to close the DB connection?
In short (in pseudo-code):
MongoClient.connect(url, function(err, db) {
if (err) throw err;
fs.readDir(path, function(err, files) {
for file in files {
if (interesting(file)) {
fs.readFile(file, function(err, data) {
doc = turnDataIntoDocument(data);
db.collection('foo').insert(doc);
});
}
}
});
// This is the part that won't work right:
db.close()
});
Obviously, the db.close()
could happen at any time, probably before all the files are processed, or usually before the directory is even fully-read.
I know there are libraries for dealing with control flow, but I feel like I should understand how to do this at a more fundamental level rather than depending on a library for something so simple - don't close the connection until I'm done with it.
Aucun commentaire:
Enregistrer un commentaire