-
Notifications
You must be signed in to change notification settings - Fork 3
/
Utest.js
95 lines (83 loc) · 2.5 KB
/
Utest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env node
const chalk = require("chalk");
const boxen = require("boxen");
const yargs = require("yargs");
const fetch = require("node-fetch");
const fs = require("fs");
const version = require("./package.json").version;
const { boxenOptions } = require("./styling/style");
const vmessage = chalk.white.bold(`Utest version: ${version}`);
const msgBox = boxen(vmessage, boxenOptions);
const argv = yargs
.usage("Usage: $0 [option]")
.alias("f", "file")
.nargs("f", 1)
.describe("f", "Load a file")
.demandOption(["f"])
.help("h")
.alias("h", "help")
.alias("v", "version")
.alias("V", "version")
.alias("j", "json")
.describe("json", "print in JSON format")
.version(`${msgBox}`)
.describe("version", "show version information").argv;
// Create stream with the file
const s = fs.createReadStream(argv.file);
let urlList;
s.on("data", (buf) => {
// Get all the URL links from the file
urlList = buf
.toString()
.match(/(http|https)(:\/\/)([\w+\-&@`~#$%^*.=/?:]+)/gi);
});
//print responses colorized
function printResponse(data) {
for (var item of data) {
if (item.status == 200) {
console.log(
chalk.green.bold(`[GOOD] Status: [${item.status}] ${item.url}`)
);
} else if (item.status == 400 || item.status == 404) {
console.log(chalk.red.bold(`[BAD] Status: [${item.status}] ${item.url}`));
} else {
console.log(
chalk.grey.bold(`[UNKNOWN] Status: [${item.status}] ${item.url}`)
);
}
}
}
function checkStatus(data) {
for (var item of data) {
if (item.status == 400 || item.status == 404 || item.status == "UNKNOWN") {
return 1;
}
}
return 0;
}
s.on("end", async () => {
var responseStatusByUrl = [];
var statusResponseForUrl;
//Iterate through the links and check their status
await Promise.all(
urlList.map(async (url) => {
try {
const urlTest = await fetch(url, { method: "head", timeout: 1500 });
statusResponseForUrl = { url: `${url}`, status: `${urlTest.status}` };
responseStatusByUrl.push(statusResponseForUrl);
} catch (error) {
statusResponseForUrl = { url: `${url}`, status: "UNKNOWN" };
responseStatusByUrl.push(statusResponseForUrl);
}
})
);
if (argv.json) {
console.log(JSON.stringify(responseStatusByUrl));
} else {
printResponse(responseStatusByUrl);
}
process.exit(checkStatus(responseStatusByUrl));
});
process.on("exit", function (code) {
return console.log(`About to exit with code ${code}`);
});