// _module.js const vm = require('vm'); // one module of node, it can transfer string into real javascript code that v8 can recognize and execute. const fs = require('fs'); // read the file. const moduleWrapFn = require('moduleWrapFn'); // our moudleWrapFn.js function_Module() { this.exports = {}; }
_Module.prototype._compile = function(filePath) { const source = fs.readFileSync(filePath,'utf-8'); // that's why require is a synchronouse function. const fn = vm.runInThisContext(moduleWrapFn(source)); // this fn is exported _module exactly . return fn; }
const newModule = new _Module(); module.exports = newModule // return real _module object.
module.exports = function(filePath) { const fn = _module._compile(filePath); return fn(_module).exports; // export what hang on the _module.exports. }
All functional module we have done. Let’s test.
1 2 3 4 5
// main.js const _require = require('_require'); const add = _require('add'); // caution: We use our _require instead of require to import add module.
console.log('5+6 =',add(5,6)); // => 5+6 = 11
the result =>
build a https server in local
https need cerfiticate. in this case I use self-signed to generate a cerifiicate.(ps: ubuntu 16.04 LTS)
first need a private key, then use key to create a sign file, finally use above two file to generate the certificate file. type these codes in terminal.
var express = require('express'); var app = express(); var path = require('path'); var fs = require('fs');
var http = require('http'); var https = require('https');
var privateKey = fs.readFileSync(path.join(__dirname,'./private.pem'),'utf8'); var certificate = fs.readFileSync(path.join(__dirname,'./file.crt'),'utf8'); var credentials = {key: privateKey, cert:certificate};
var httpServer = http.createServer(app); var httpsServer = https.createServer(credentials,app);
var PORT = 8000; var SSLPORT = 8001;
httpServer.listen(PORT, () => { console.log('HTTP Server is running on: http://localhost:%s',PORT); });
httpsServer.listen(SSLPORT, () => { console.log('HTTPS Server is running on: http://localhost:%s',SSLPORT); });
app.get('/', function(req, res) { req.protocol === 'https' ? res.status(200).send('This is https visit') : res.status(200).send('This is http visit'); });