nodejs建立靜態檔案服務
阿新 • • 發佈:2019-01-14
//獲取本機ip
const getLocalIP = function () {
const os = require('os')
var ifaces = os.networkInterfaces();
var ip = '';
for (var dev in ifaces) {
ifaces[dev].forEach(function (details) {
if (ip === '' && details.family === 'IPv4' && !details.internal) {
ip = details.address;
return ip;
}
});
}
}
//開啟預設瀏覽器
const openDefaultBrowser = function (url) {
var exec = require('child_process').exec;
console.log(process.platform)
switch (process.platform) {
case "darwin":
exec('open ' + url);
break;
case "win32":
exec ('start ' + url);
break;
default:
exec('xdg-open', [url]);
}
}
openDefaultBrowser('https://www.baidu.com')
//使用現有包的靜態伺服器
const connect = require('connect');
const servestatic = require('serve-static');
const app = connect();
app.use(servestatic(__dirname+"/public"));// servestatic(靜態檔案的入口目錄)
app.listen(3000);
//使用流建立簡單的靜態服務
const http = require('http');
const fs = require('fs');
const zlib = require('zlib');
http.createServer((req, res) => {
res.writeHead(200, {
'content-encoding': 'gzip'
});
fs.createReadStream(__dirname + '/login.html')
.pipe(zlib.createGzip())
.pipe(res);
}).listen(8080)