In my script, node.js reads text files and generates text itself. At the end, I have five "text parts", and want to add them to one file. For this step, it must be considered that the sequence is important, so unfortunately the great async technique of node is obstructive. How would you handle this?
The five text parts consists of:
- Read File "head.txt" and than write/append its text (not much data) to the file
- Text (not much data) generated by node itself -> write/append its text to the file
- Text (large data) generated by node itself (loop)
- Text (large data) generated by node itself (loop)
- Read File "footer.txt" and than write/append its text (normal size) to the file
var fs = require('fs');
var filename = "content.txt";
// (1) Read 'head.txt'
fs.readFileSync('head.txt', 'utf8', function (err, head) {
if (err) {
return console.log('Could not read file.');
}
fs.appendFile(filename, head);
//var writeStream = fs.createWriteStream(filename);
//writeStream.write(head);
});
// (2)
var a = '...';
var b = '...';
var ab = a + b;
//var writeStream = fs.createWriteStream(filename);
//writeStream.write(ab);
//writeStream.end();
fs.appendFileSync(filename, ab);
// (3)
var writeStream = fs.createWriteStream(filename);
for (i = 0; i < xzy.length; i++) {
writeStream.write('...' + xyz[i] + '...');
}
//writeStream.end();
// (4)
var writeStream = fs.createWriteStream(filename);
for (i = 0; i < xyz.length; i++) {
writeStream.write('...' + xyz[i] + '...');
}
//writeStream.end();
// (5) Read 'footer.txt'
fs.readFileSync('footer.txt', 'utf8', function (err, footer) {
if (err) {
return console.log('Could not read file.');
}
var writeStream = fs.createWriteStream(filename);
writeStream.write(footer);
//writeStream.end();
});
/*writeStream.on('finish', function () {
console.log('finish');
});
writeStream.on('close', function () {
console.log('close');
});*/