Web 的王者 Javascript 愈战愈勇
Posted on Tue 02 March 2021 in Program
Quote
Reading make a full man; conference a ready man; and writing an exact man. And therefore, if a man write little, he had need have a great memory; if he confer little, he had need have a present wit; and if he read little, he had need have much cunning, to seem to know that he doth not.
读书使人充实,讨论使人机智,笔记使人准确。因此不常做笔记者须记忆力特强,不常讨论者须天生聪颖,不常读书者须欺世有术,始能无知而显有知。
Histories make men wise; poets witty; the mathematics subtile; natural philosophy deep; moral grave; logic and rhetoric able to contend. Abeunt studia in morse. (Studeis go to make up a man’s character.)
读史使人明智,读诗使人灵秀,数学使人周密,科学使人深刻,伦理学使人庄重,逻辑修辞之学使人善辩;凡有所学,皆成性格。
-- 培根
Thinking
从语言设计层面来说, JavaScript 不是一个高质量的语言,我曾经写过一篇吐槽文章, "C++程序员眼中丑陋的 JS".
尽管如此, 在浏览器中,服务器中,移动设备上甚至嵌入式系统中 JavaScript 的身影无处不在, nodejs 的兴起使得 JavaScript 从前端拓展到后端,成为全栈语言. 它生机勃勃, 成长迅速, 在互联网世界中独领风骚. 2015 年发布的 ECMAScript 标准, JavaScript 从3.0 逐渐到了 6.0, 现代语言的高级特性它基本上都有, 其安全性和可靠性也得到了提高.
Javascript 的性能一直是让人诟病的地方,自从有了 WebRTC 和 WebAssembly, 在 Web 页面上也能做很多以前需要用 C++ 语言才能实现的应用,比如网络视频会议, 3D 游戏等.
NodeJS, 和 Express/Koa/Hapi, React/Angular/VUE 等框架, npm, gulp, webpack 等工具, Javascript 的生态系统也建立起来了.
作为一名全栈工程师,有必要回炉再造, 系统地复习和学习 JavaScript.
Codes
一百行写一个 Web Restful 服务
- vi index.js
"use strict"
const fs = require('fs');
const http = require('http');
const https = require('https');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3');
const log4js = require("log4js");
log4js.configure({
appenders: {
'stdout': { type: 'stdout' },
'jshelper': {
filename: "pt_metrics.log",
type: 'dateFile',
pattern: "yyyy-MM-dd",
keepFileExt: true,
maxLogSize: 1024 * 1024 * 10, //1024 * 1024 * 1 = 10M
backups: 2,
alwaysIncludePattern: true,
daysToKeep: 7,
layout: {
type : "pattern",
pattern : "%d{ABSOLUTE} %[%-5p%] %c %x{singleLine}",
tokens: {
singleLine : function(logEvent) {
// logEvent.data is an array that contains the arguments to the log.info() call
return JSON.stringify(logEvent.data[0]);
}
}
}
}
},
categories: { default: {
appenders: ["stdout","jshelper"],
level: "info" }
}
});
const express = require('express');
const app = express();
const path = require('path');
const logger = log4js.getLogger("jshelper");
const PORT = 8080;
const options = {
index: "index.html"
};
const db = new sqlite3.Database('./report.db', (err) => {
if (err) {
console.error("Erro opening database " + err.message);
} else {
db.run(`CREATE TABLE report(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
type NVARCHAR(32) NOT NULL,
category NVARCHAR(32),
label NVARCHAR(64),
content TEXT NOT NULL,
time Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)`, (err) => {
if (err) {
console.log("Table already exists.");
}
let insert = 'INSERT INTO report (type, category, label, content) VALUES (?,?, ? ,?)';
db.run(insert, ["event", "system", "PT", "startup"]);
});
}
});
app.use('/', express.static(path.join(__dirname, '/'), options));
// parse requests of content-type - application/x-www-form-urlencoded and application/json
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/api/v1/ping', (req, res) => {
res.json({"message": "Healthy", "serviceState": "online"});
});
app.post('/api/v1/events', function(request, response) {
console.log("received event: ", request.body); // your JSON
response.send({"result": "OK"});
logger.info(request.body);
});
const httpServer = http.createServer(app);
console.log('Running local tool http page on ' + PORT);
httpServer.listen(PORT);
Words
- asteroid
collapsed
英 /kəˈlæpst/ 美 /kəˈlæpst/ 全球(英国)
adj. 倒塌的;暴跌的;收缩的;倾陷了的
v. 倒塌;崩溃(collapse的过去分词);价格暴跌
Share prices collapsed after news of poor trading figures. 在交易数额不佳的消息公布后,股票价格暴跌。
- mammal
英 /ˈmæml/ 美 /ˈmæml/ 全球(美国)
n. [脊椎] 哺乳动物
The existense of dinosaurs blocked the evolution of mailams
- Extinction
Extinction 英 /ɪkˈstɪŋkʃn/ 美 /ɪkˈstɪŋkʃn/ 全球(美国)
n. 灭绝;消失;消灭;废止
Mass extinction events have played an important part in the evolution of life.