There is also, on their website, a link to a node.js implementation, and that's what I was planning to use on my server.
exports is defined, if I wanted to, and that would give me a way of using the exact same file on both the client and the server. However, I decided to hade two files since I wanted to put the node module with my global node modules for use in other projects.
Taking it to the next level
Today I decided that I wanted to try and do the same thing with the SyntaxHighlighter library. That turned out to be a little trickier.
When Alex wrote version 3.x of SyntaxHighlighter he, wisely, decided that it should be a CommonJS module. He even wrote a test that uses it in node.js. The problem with his implementation lies in what features he exposed.
When you run SyntaxHighlighter in a browser, you make a call to a function that gets all HTML-elements containing code (by default the
<pre>-elements). Then it gets their
innerHTML attribute and does its magic with it. When it's done it replaces the
<pre>-element with the new pretty
<div>-element containing all the highlighted code.
This doesn't work so well on the server since it uses DOM-manipulation and the server side has no DOM (although some people are trying to build DOM access as a node module but that feels dirty to me).
What Alex did was expose a function that renders a string containg the code into a string containing the pretty
<div>-element. Like this (from his website):
That's great if you have a lot of code examples in a database that. I however have all my code examples embedded in blog posts, surrounded by a lot of text and HTML. I want it to work in the same way as it does client-side.
So I hacked it. It's not pretty, it still contains a lot of code that I don't need and it involves a bit of XRegExp magic (XRegExp is awesome btw).
What it does do is work, beautifully. And now I can do this:
It also saves my readers from having to download 166 KB worth of data distributed over six HTTP requests, and that, ladies and gentlemen, is a win.