Storing Data in Files
Though you probably wouldn’t choose to store data in a text file over a database, there might be times when you want to write to and read from something highly portable—for example, if you were managing values in a config file. Writing to a file can’t give us the control over individual properties a data store can, of course, and it’s very slow, but there are still applications where a text file makes sense. Like writing to a database, writing to a file is done asynchronously, so if we want verification that it was done we’ll need to take any dependent actions from within a callback:
var connect = require("connect"),
fs = require("fs");
connect(
connect.static(__dirname + "/public"),
connect.bodyParser(),
function(req, res) {
var firstName = req.body.firstName,
lastName = req.body.lastName,
userName = firstName + " " + lastName,
stream;
if (firstName || lastName) {
// create a stream, and create the file if it doesn't exist
stream = fs.createWriteStream("user_name.txt");
} else {
return;
}
stream.on("open", function() {
// write to and close the stream at the same time
stream.end((firstName + "," + lastName + "\n"), "utf-8");
var html = "<!doctype html>" +
"<html><head><title>Hello " + userName + "</title></head>" +
"<body><h1>Hello, " + userName + "!</h1></body></html>";
res.end(html);
});
}
).listen(8000);Setting the data is easy, but it’s also fragile. We have to check that we’ve actually received data to avoid overwriting good data with bad, and if we had ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access