Übung 07 - Node
7.1 File Generatoren
Number File Generator
import * as process from "process";
import fs from 'fs';
const number = process.argv[process.argv.length -1]
let text = "";
for (let i = 1; i <= number; i++) {
text += i + " .\n";
}
text = text.substring(0, text.length-1);
fs.writeFile('testfile.txt', text, function (err) {
if (err) throw err;
console.log('Saved!');
});
Alpha File Generator
import process from 'process'
import fs from 'fs'
const number = process.argv[process.argv.length -1]
let text = "";
for (let i = 1; i <= number; i++) {
text += numbersToLetters(i) + "\n"
}
text = text.substring(0, text.length-1);
fs.writeFile('alphafile.txt', text, function (err) {
if (err) throw err;
console.log('Saved!');
});
// function numbersToLetters from Flambino on Stackexchange
// https://codereview.stackexchange.com/a/16129
function numbersToLetters(number) {
let baseChar = ("A").charCodeAt(0),
letters = "";
do {
number -= 1;
letters = String.fromCharCode(baseChar + (number % 26)) + letters;
number = (number / 26) >> 0; // quick `floor`
} while(number > 0);
return letters;
}
7.2 Performance Merge
Merge Files
import fs from 'fs/promises'
import * as process from "process";
const file1 = process.argv[process.argv.length - 1];
const file2 = process.argv[process.argv.length - 2];
console.time("merge");
(async _=> {
const [text1, text2] = await Promise.all([fs.readFile(file1, 'utf8'), fs.readFile(file2, 'utf8')])
let arr1 = text1.split("\n");
let arr2 = text2.split("\n");
const text = interleave(arr1, arr2);
const output = text.join('\n')
fs.writeFile('mergeFileRes.txt', output, function (err) {
if (err) throw err;
console.log('Saved!');
});
console.timeEnd("merge");
})();
// interleave function taken from Mulan on stackoverflow
// https://stackoverflow.com/a/47061616/15212696
const interleave = ([x, ...xs], ys = []) =>
x === undefined
? ys // base: no x
: [x, ...interleave(ys, xs)] // inductive: some x
Merge Streams
const fs = require("fs");
const files = process.argv.slice(2);
console.time("merge")
const stream1 = fs.createReadStream(files[0], "utf8");
const stream2 = fs.createReadStream(files[1], "utf8");
const lines1 = [], lines2 = [];
stream1.on("data", process_chunk(lines1));
stream2.on("data", process_chunk(lines2));
stream1.on("end", output);
stream2.on("end", output);
let result = "";
let count = 0;
function output() {
count += 1;
if (count === 2) {
lines1.forEach((line, i) => result += line + "\n" + lines2[i] + "\n")
}
fs.writeFile('mergeStreamsRes.txt', result.substring(0, result.length - 1), function (err) {
if (err) throw err;
});
console.timeEnd("merge")
}
function process_chunk(lines) {
return function (chunk) {
let i = 0;
chunk.split("\n").forEach(function (line) {
if (!lines[i]) {
lines[i] = '';
}
lines[i++] += line;
});
}
}
Performanzmessung:
Merge Files: 1.716ms
Merge Streams: 7.352ms
7.3 Express Server
const express = require('express');
const fs = require('fs');
const fileUpload = require('express-fileupload')
const app = express();
const port = 3000;
app.use(fileUpload());
app.get('/', (req, res) => {
res.writeHead(200, {"Content-Type": "text/html"});
res.end('<!DOCTYPE html>\n' +
'<html lang="en">\n' +
'<head>\n' +
' <meta charset="UTF-8">\n' +
' <title>Merge Files</title>\n' +
'</head>\n' +
'<body style="font-family: Calibri">\n' +
'<h2>Wählen Sie zwei Dateien zum Mergen aus.</h2>\n' +
'<form enctype="multipart/form-data" method="POST" action="/upload">\n' +
' <input name="first" type="file">\n' +
' <input name="second" type="file">\n' +
' <input type="submit">\n' +
'</form>\n' +
'</body>\n' +
'</html>')
})
app.post('/upload', function (req, res) {
let first = req.files.first.data.toString('utf8').split("\n");
let second = req.files.second.data.toString('utf8').split("\n");
const text = interleave(first, second).join('\n');
fs.writeFile('mergedResult.txt', text, function (err) {
if (err) throw err;
});
res.send(`<h2 style="font-family: Calibri">Die Ergebnisdatei kann
<a href="/download" target="_blank">hier</a> heruntergeladen werden und hat folgenden Inhalt:</h2>` + text);
})
app.get('/download', function(req, res){
const file = "mergedResult.txt";
res.download(file)
})
// interleave function taken from Mulan on stackoverflow
// https://stackoverflow.com/a/47061616/15212696
const interleave = ([x, ...xs], ys = []) =>
x === undefined
? ys // base: no x
: [x, ...interleave(ys, xs)] // inductive: some x
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})