94 lines
2.2 KiB
JavaScript
94 lines
2.2 KiB
JavaScript
import dns from 'node:dns';
|
|
import color from 'chalk';
|
|
import util from 'node:util';
|
|
|
|
const IP_V = 4; // we use IP protocol version 4
|
|
const URL = 'google.de';
|
|
|
|
// 1.
|
|
const getIpBy = (url, ip = 4) => {
|
|
return new Promise((resolve, reject) => {
|
|
dns.lookup(url, ip, (error, data) => {
|
|
if (error) {
|
|
reject(error);
|
|
} else {
|
|
resolve({ address: data, family: ip });
|
|
}
|
|
});
|
|
});
|
|
};
|
|
|
|
// 2.
|
|
// Promises Unterobjekt von Node
|
|
const getPromisesIpBy = (url, ip = 4) => {
|
|
return dns.promises.lookup(url, ip);
|
|
};
|
|
|
|
// 3.
|
|
// Promisify Helferfunktion
|
|
const getPromisifyIpBy = util.promisify(dns.lookup);
|
|
// 4.
|
|
// Async await
|
|
const getAsyncIpBy = async (url, ip) => {
|
|
try {
|
|
const result = await dns.promises.lookup(url, ip);
|
|
return result;
|
|
} catch (err) {
|
|
console.log(err);
|
|
throw new Error(err);
|
|
}
|
|
};
|
|
|
|
// Test Cases:
|
|
// =============================
|
|
getIpBy(URL, IP_V)
|
|
.then((data) => {
|
|
console.log(data);
|
|
})
|
|
.catch((err) => {
|
|
console.log(color.red(err));
|
|
});
|
|
|
|
getPromisesIpBy(URL)
|
|
.then((data) => {
|
|
console.log(data);
|
|
})
|
|
.catch((err) => {
|
|
console.log(color.red(err));
|
|
});
|
|
|
|
getPromisifyIpBy(URL, IP_V)
|
|
.then((data) => {
|
|
console.log(data);
|
|
})
|
|
.catch((err) => {
|
|
console.log(color.red(err));
|
|
});
|
|
|
|
getAsyncIpBy(URL, IP_V)
|
|
.then((data) => {
|
|
console.log(data);
|
|
})
|
|
.catch((err) => {
|
|
console.log(color.red(err));
|
|
});
|
|
|
|
/* Übung 13: Das Telefonbuch des Internets
|
|
|
|
Vielleicht hast du einmal die Webseite www.nodejs.com besucht? Dann hat dein Computer die so genannte IP-Adresse des Servers www.nodejs.org herausgefunden.
|
|
|
|
Ähnlich wie ein Telefonbuch ordnet das Domain Name System (DNS) jedem Server (Host) eine eindeutige IP-Adresse zu, unter der er über das Internet erreichbar ist.
|
|
|
|
Die Node.js-API bietet eine Funktion, um Namen im DNS nachzuschlagen: dns.lookup(…).
|
|
|
|
Die Übung besteht nun darin, obiges Beispiel so umzuschreiben, dass der Aufruf von dns.lookup(…) in eine Wrapper-Funkion verpackt wird.
|
|
|
|
Es sollen drei verschiedene Lösungen erstellt werden:
|
|
|
|
1. Ausführliche Variante mit eigenem Promise-Objekt als Ummantelung
|
|
2. Kurze Variante mit Promises-Unterobjekt (dns.promises)
|
|
3. Promisify-Variante mit util.promisify(…)
|
|
4. Async await Variante
|
|
|
|
*/
|