dev.js 5.23 KB
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const request = require('request');
const mime = require('mime');
const parseRange = require('range-parser');
const cluster = require('cluster');
const express = require('express');
const chokidar = require('chokidar');
const EventSource = require('eventsource');
const {createApp} = require('./create-app.js');
const {createBundleRenderer} = require('vue-server-renderer');
const {devServer, readFile, publish} = require('./build/dev-server.js');

const watcher = {
    paths: ['./apps', './create-app.js', './doraemon', './config', './utils'],
    options: {}
};

let renderer;
let realyPromise;
let template = fs.readFileSync(path.join(__dirname, './src/index.html'), 'utf-8');

if (cluster.isMaster) {
    const masterApp = express();

    realyPromise = devServer(masterApp, params => {
        renderer = createBundleRenderer(params.bundle, Object.assign(params.options, {
            runInNewContext: false,
            template
        }));
    });
    let childWorker = cluster.fork();

    cluster.on('message', (worker, msg) => {
        if (msg.action === 'ssr_request') {
            realyPromise.then(() => {
                renderer.renderToString(msg.context, (err, html) => {
                    worker.send({action: 'ssr_request', html, err: err && JSON.stringify(err)});
                });
            });
        }

        // else if (msg.action === 'ssr_static_file') {
        //     worker.send({
        //         action: 'ssr_static_file',
        //         content: readFile(msg.url),
        //         url: msg.url
        //     });
        // }
    });
    chokidar.watch(watcher.paths, watcher.options).on('change', pathStr => {
        console.log(`${pathStr} changed`);
        childWorker && childWorker.kill();
        childWorker = cluster.fork().on('listening', address => {
            console.log(`worker is restarted at ${address.port}`);
            publish({action: 'reload'});
            console.log('client is refresh');
        });
    });
    masterApp.listen(6005, () => {
        console.log('master is started');
    });
} else {
    const app = express();

    // app.use((req, res, next) => {
    //     if (req.method !== 'GET') {
    //         return next();
    //     }
    //     if (req.get('accept') === 'text/event-stream') {
    //         return next();
    //     }
    //     request.get(`http://localhost:6005${req.url}`, (error, httpResponse, body) => {
    //         if (httpResponse.statusCode === 404 || error) {
    //             return next();
    //         } else {
    //             res.set(httpResponse.headers);
    //             return res.send(body);
    //         }
    //     });
    // });
    // app.use((req, res, next) => {
    //     process.send({action: 'ssr_static_file', url: req.url});
    //     let event = msg => {
    //         if (msg.action === 'ssr_static_file' && msg.url === req.url) {
    //             process.removeListener('message', event);
    //             let content = msg.content;

    //             if (content === false) {
    //                 return next();
    //             }

    //             res.setHeader('Accept-Ranges', 'bytes');
    //             if (req.headers.range) {
    //                 const ranges = parseRange(content.length, req.headers.range);

    //                 if (ranges === -1) {
    //                     res.setHeader('Content-Range', 'bytes */' + content.length);
    //                     res.statusCode = 416;
    //                 }
    //                 if (ranges !== -2 && ranges.length === 1) {
    //                     res.statusCode = 206;
    //                     let length = content.length;

    //                     res.setHeader(
    //                         'Content-Range',
    //                         'bytes ' + ranges[0].start + '-' + ranges[0].end + '/' + length
    //                     );
    //                     content = content.slice(ranges[0].start, ranges[0].end + 1);
    //                 }
    //             }
    //             res.setHeader('Content-Type', mime.lookup(req.path) + '; charset=UTF-8');
    //             res.setHeader('Content-Length', content.length);
    //             res.statusCode = res.statusCode || 200;
    //             return res.send(content);
    //         }
    //     };

    //     process.on('message', event);
    // });

    // let es = new EventSource('http://localhost:6005/__webpack_hmr');
    // let clients = {};
    // let clientId = 0;

    // es.onmessage = (event) => {
    //     _.each(clients, client => {
    //         client.write('data: ' + event.data + '\n\n');
    //     });
    // };
    // app.use('/__webpack_hmr', (req, res) => {
    //     req.socket.setKeepAlive(true);
    //     res.writeHead(200, {
    //         'Access-Control-Allow-Origin': '*',
    //         'Content-Type': 'text/event-stream;charset=utf-8',
    //         'Cache-Control': 'no-cache, no-transform',
    //         Connection: 'keep-alive',
    //         'X-Accel-Buffering': 'no'
    //     });
    //     res.write('\n');
    //     let id = clientId++;

    //     clients[id] = res;
    //     req.on('close', function() {
    //         delete clients[id];
    //     });
    // });

    createApp(app);
}