-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathindex.js
54 lines (49 loc) · 1.6 KB
/
index.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
const translate = require("google-translate-cn-api");
const stdio = require("stdio");
const express = require("express");
const date = require("date-and-time");
const app = express();
const ops = stdio.getopt({
port: { key: "p", args: 1, description: "running port", default: 30031 },
domain: {
key: "d",
args: 1,
description: "google translate port",
default: "com",
},
});
const port = parseInt(ops.port);
const domain = ops.domain;
// log functionalities
const timeFormat = date.compile("YYYY/MM/DD HH:mm:ss");
const prettyJson = (object) =>
JSON.stringify(object)
.replace(/"/g, "")
.replace(/([,:])/g, "$1 ");
function log(req, text, status) {
const now = date.format(new Date(), timeFormat);
let ip = req.connection.remoteAddress;
const params = prettyJson(req.query);
console.log(`${now} [${ip}] ${status} "${text}" ${params}`);
}
// express server
app.get("/", function (req, res) {
const text = req.query.text;
delete req.query.text;
translate(text, { ...{ domain: domain }, ...req.query })
.then((resp) => res.json(resp) && log(req, text, 200))
.catch((resp) => res.status(400).json(resp) && log(req, text, 400));
});
app.listen(port, function () {
console.log(
"\n ___ _____ ___\n" +
" / __|_ _| / __| ___ _ ___ _____ _ _\n" +
" | (_ | | | \\__ \\/ -_) '_\\ V / -_) '_|\n" +
" \\___| |_| |___/\\___|_| \\_/\\___|_|\n\n"
);
console.log(`App listening on port ${port}!`);
console.log(
`Default Google Translate domain: https://translate.google.${domain}/`
);
console.log("Incoming requests will be listed below:\n");
});