我试图通过从头开始构建Web服务器来变得更加熟悉JS。我具有以下用于初始化基本Web服务器的类:
// @flow
'use strict';
import fs from 'fs';
type CertPath = { key: string, cert: string };
export class Server {
constructor(certPaths: CertPath){
this.setCertPath(certPaths)
}
certPath: CertPath;
forceSecure = false;
https = require('https');
port = 443;
setCertPath = (certPaths: Object) => {
this.certPath = certPaths;
};
connection = this.https.createServer({
key: fs.readFileSync(this.certPaths.key),
cert: fs.readFileSync(this.certPaths.cert)
});
forceSecureConnection = (bool = true) => {
this.forceSecure = bool;
return this;
};
enableServer = (port = 443) => {
this.port = port;
this.connection.listen(port, '127.0.0.1');
};
}
然后我将启动服务器:
const web = new Server("Throw some error, PLEASE!");
web.enableServer();
由于https://github.com/facebook/flow/issues/1409,我不希望CertPath类型在构造函数中失败。但是,如果执行this.certPath = 'anything other than type CertPath'
这是我的.babelrc
{
"presets": [
"flow",
["env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"transform-class-properties"
]
}