Skip to content

Instantly share code, notes, and snippets.

@3den
Created April 20, 2017 18:44
Show Gist options
  • Save 3den/1416fc25a47208f73be8dbbc7e98ca52 to your computer and use it in GitHub Desktop.
Save 3den/1416fc25a47208f73be8dbbc7e98ca52 to your computer and use it in GitHub Desktop.
React On Rails Node Server
/* eslint-disable no-console */
module.exports = class Handler {
constructor() {
this.queue = [];
this.initialized = false;
}
initialize() {
if (this.initialized) {
console.log('Reloading server bundle must be implemented by restarting the node process!');
return;
}
console.log(`Processing ${this.queue.length} pending requests`);
let callback;
// eslint-disable-next-line no-cond-assign
while (callback = this.queue.pop()) {
callback();
}
this.initialized = true;
}
handle(connection) {
const callback = () => {
const terminator = '\r\n\0';
let request = '';
connection.setEncoding('utf8');
connection.on('data', (data) => {
console.log(`Processing chunk: ${data}`);
request += data;
if (data.slice(-terminator.length) === terminator) {
request = request.slice(0, -terminator.length);
// eslint-disable-next-line no-eval
const response = eval(request);
connection.write(`${response}${terminator}`);
request = '';
}
});
};
if (this.initialized) {
callback();
} else {
this.queue.push(callback);
}
}
};
/* eslint-disable no-console */
const net = require('net');
const fs = require('fs');
const Handler = require('./node/Handler.js');
const nodeSockPath = './node/node.sock';
const bundlePath = '../app/assets/webpack/';
const bundleFileName = 'webpack-bundle.js';
const bundleFilePath = `${bundlePath}${bundleFileName}`;
const handler = new Handler();
function loadBundle() {
/* eslint-disable */
require(bundleFilePath);
/* eslint-enable */
console.log(`Loaded server bundle: ${bundleFilePath}`);
handler.initialize();
}
try {
fs.mkdirSync(bundlePath);
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
} else {
loadBundle();
}
}
fs.watchFile(bundleFilePath, (curr) => {
if (curr && curr.blocks && curr.blocks > 0) {
loadBundle();
}
});
const unixServer = net.createServer((connection) => {
handler.handle(connection);
});
unixServer.listen(nodeSockPath);
process.on('SIGINT', () => {
unixServer.close();
process.exit();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment