Skip to content

Instantly share code, notes, and snippets.

@mklymyshyn
Created December 13, 2014 14:56
Show Gist options
  • Save mklymyshyn/e99b7b56ea268bbaeded to your computer and use it in GitHub Desktop.
Save mklymyshyn/e99b7b56ea268bbaeded to your computer and use it in GitHub Desktop.
var http = require('http'),
browserify = require('browserify'),
literalify = require('literalify'),
path = require("path"),
url = require("url"),
fs = require("fs")
React = require('react');
require('node-jsx').install();
var Hello = React.createFactory(require('./src/hello.jsx'));
http.createServer(function(request, response) {
if (request.url == '/') {
var HelloHtml = React.renderToString(Hello({}));
var data = '' +
'<script src="bower_components/react/react-with-addons.js"></script>' +
'<script src="bower_components/react/JSXTransformer.js"></script>' +
'<div id=example>' + HelloHtml + '</div>' +
'<script src=./build/hello.js></script>' +
// This script renders the component in the browser, referencing it
// from the browserified bundle, using the same props we used to render
// server-side. We could have used a window-level variable, or even a
// JSON-typed script tag, but this option is safe from namespacing and
// injection issues, and doesn't require parsing
'<script type="text/javascript">' +
'var React = require("react/addons");' +
//'var Hello = React.createFactory(require("Hello"));' +
//'React.render(Hello({}), document.getElementById("example"))' +
'</script>';
response.setHeader('Content-Length', data.length);
response.end(data);
} else {
var uri = url.parse(request.url).pathname,
filename = path.join(process.cwd(), uri);
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}
}).listen(3000, function(err) {
if (err) throw err
console.log('Listening on 3000...')
})
// A utility function to safely escape JSON for embedding in a <script> tag
function safeStringify(obj) {
return JSON.stringify(obj).replace(/<\/script/g, '<\\/script').replace(/<!--/g, '<\\!--')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment