Commit ed9ac7e4 authored by rockyl's avatar rockyl

add code serve

parent 534c71e3
#!/usr/bin/env node
/**
* Created by rockyl on 2019-12-25.
*/
const program = require('commander');
const {start} = require('../src/index');
program
.option('-p, --port [string]', 'Server port', '7788')
.option('-f, --file [string]', 'Target file')
.parse(process.argv);
if(!program.file){
console.error('Target file must be specified');
}else{
start(program);
}
......@@ -12,4 +12,5 @@ program
.command('dev', 'Build project automatic').alias('d')
.command('build', 'Publish project').alias('b')
.command('upload', 'Upload project to oss').alias('u')
.command('code-serve', 'Code sync serve')
.parse(process.argv);
......@@ -30,7 +30,7 @@ function handler(jsonPath, proxy) {
if (proxy) {
const target = proxy.startsWith('http') ? proxy : `http://${proxy}`;
console.log(`proxy: ${target}${url}`)
console.log(`proxy: ${target}${url}`);
Object.entries(headers).forEach(([key, val]) => response.setHeader(key, val));
return proxyServer.web(request, response, { target }, err => {
console.log(err);
......
/**
* Created by rockyl on 2019-12-25.
*/
const Server = require('socket.io');
const path = require('path');
const fs = require('fs-extra');
exports.start = function (options) {
const sockets = [];
let watching = false;
fs.watch(options.file, {}, (eventType) => {
if (watching) {
if (eventType === 'change') {
const code = fs.readFileSync(options.file, 'utf-8');
for(let socket of sockets){
socket.emit('edit-save', code);
}
}
}
});
let server = Server(options.port);
server.on('connection', function (socket) {
sockets.push(socket);
socket.on('disconnect', function () {
sockets.splice(sockets.indexOf(socket), 1);
});
socket.on('edit-open', function (data) {
fs.ensureDir(path.dirname(options.file));
watching = false;
fs.writeFileSync(options.file, data);
setTimeout(function () {
watching = true;
}, 500);
})
});
};
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment