Blog like it's 1999
Journo = module.exports =
Journo is a blogging program, with a few basic goals. To wit:
Write in Markdown.
Publish to flat files.
Publish via Rsync.
Maintain a manifest file (what's published and what isn't, pub dates).
Syntax highlight code.
Publish a feed.
Quickly bootstrap a new blog.
Preview via a local server.
... let's go through these one at a time:
We'll use the excellent marked module to compile Markdown into HTML, and Underscore for many of its goodies later on. Up top, create a namespace for shared values needed by more than one function.
marked = require 'marked'_ = require 'underscore'shared =
To render a post, we take its raw
source, treat it as both an Underscore
template (for HTML generation) and as Markdown (for formatting), and insert it
into the layout as
=catchErrors ->do loadLayoutsource or= fsreadFileSync postPath postvariables = renderVariables postmarkdown = _templatesourcetoString variablestitle = detectTitle markdowncontent = markedparser markedlexer markdownsharedlayout _extend variablestitlecontent
A Journo site has a layout file, stored in
layout.html, which is used
to wrap every page.
=return layout if not force and layout = sharedlayoutshared.layout = _templatefsreadFileSync'layout.html'toString
A blog is a folder on your hard drive. Within the blog, you have a
folder for blog posts, a
public folder for static content, a
file for the layout which wraps every page, and a
journo.json file for
configuration. During a
build, a static version of the site is rendered
site folder, by rsyncing over all static files, rendering and
writing every post, and creating an RSS feed.
fs = require 'fs'path = require 'path'require 'child_process'= ->do loadManifestfsmkdirSync'site' unless fsexistsSync'site'exec "rsync -vur --delete public/ site"throw err if errfor post in folderContents'posts'html = Journorender postfile = htmlPath postfsmkdirSync pathdirnamefile unless fsexistsSync pathdirnamefilefswriteFileSync filehtmlfswriteFileSync "site/feed.rss"Journofeed
config.json configuration file is where you keep the configuration
details of your blog, and how to connect to the server you'd like to publish
it on. The valid settings are:
author (for RSS),
user@host:path location to rsync to), and
(if your server doesn't listen to SSH on the usual one).
config.json will be bootstrapped for you when you initialize a blog,
so you don't need to remember any of that.
= ->return if sharedconfigtryshared.config = JSONparse fsreadFileSync 'config.json'catch errfatal "Unable to read config.json"shared.siteUrl = sharedconfigurlreplace/\/$/''
Publishing is nice and rudimentary. We build out an entirely static version of the site and rysnc it up to the server.
= ->do Journobuildrsync 'site/images/'pathjoinsharedconfigpublish'images/'->rsync 'site/'sharedconfigpublish
A helper function for rsyncing, with logging, and the ability to wait for the rsync to continue before proceeding. This is useful for ensuring that our any new photos have finished uploading (very slowly) before the update to the feed is syndicated out.
=port = "ssh -p "child = spawn "rsync"'-vurz''--delete''-e'portfromtochildstdouton 'data' consolelog outtoStringchildstderron 'data' consoleerror errtoStringchildon 'exit'callback if callback
The "manifest" is where Journo keeps track of metadata -- the title, description, publications date and last modified time of each post. Everything you need to render out an RSS feed ... and everything you need to know if a post has been updated or removed.
manifestPath = 'journo-manifest.json'= ->do loadConfigshared.manifest = if fsexistsSync manifestPathJSONparse fsreadFileSync manifestPathelsedo updateManifestfswriteFileSync manifestPathJSONstringify sharedmanifest
We update the manifest by looping through every post and every entry in the
existing manifest, looking for differences in
mtime, and recording those
along with the title and description of each post.
= ->manifest = sharedmanifestposts = folderContents 'posts'delete manifestpostfor post of manifest when post not in postsfor post in postsstat = fsstatSync postPath postentry = manifestpostif not entry or entrymtime isnt statmtimeentry or= pubtime: statctimeentry.mtime = statmtimecontent = fsreadFileSyncpostPath posttoStringentry.title = detectTitle contententry.description = detectDescription contentpostmanifestpost= entryyes
In the future, it may make sense for Journo to have some sort of built-in facility for automatically downsizing photos from retina to regular sizes ... But for now, this bit is up to you.
We syntax-highlight blocks of code with the nifty highlight package that includes heuristics for auto-language detection, so you don't have to specify what you're coding in.
require 'highlight'markedsetOptions:Highlight code
We'll use the rss module to build a simple feed of recent posts. Start with
url configured in the
config.json. Then, each post's
title is the first header present in the
description is the first paragraph, and the date is the date you
first created the post file.
= ->RSS = require 'rss'do loadConfigconfig = sharedconfigfeed =title: configtitledescription: configdescriptionfeed_url: "/rss.xml"site_url: sharedsiteUrlauthor: configauthorfor post in sortedPosts0...20entry = sharedmanifestpostfeeditemtitle: entrytitledescription: entrydescriptionurl: postUrl postdate: entrypubtimefeedxml
We init a new blog into the current directory by copying over the contents
of a basic
= ->here = fsrealpathSync '.'if fsexistsSync 'posts'fatal "A blog already exists in "bootstrap = pathjoin__dirname'bootstrap'exec "rsync -vur --delete ."throw err if errconsolelog "Initialized new blog in "
Instead of constantly rebuilding a purely static version of the site, Journo
provides a preview server (which you can start by just typing
within your blog).
= ->http = require 'http'mime = require 'mime'url = require 'url'util = require 'util'do loadManifestserver = httpcreateServerrawPath = urlparserequrlpathnamereplace//g'' or 'index'
If the request is for a preview of the RSS feed...
if rawPath is 'feed.rss'reswriteHead 200'Content-Type': mimelookup'.rss'resend Journofeed
If the request is for a static file that exists in our
elsepublicPath = "public/" + rawPathfsexists publicPathif existsreswriteHead 200'Content-Type': mimelookuppublicPathfscreateReadStreampublicPathpipe res
If the request is for the slug of a valid post, we reload the layout, and render it...
elsepost = "posts/.md"fsexists postif existsloadLayout truefsreadFile postreswriteHead 200'Content-Type': 'text/html'resend Journorender postcontent
Anything else is a 404. (Does anyone know a cross-platform equivalent of the
elsereswriteHead 404resend '404 Not Found'serverlisten 1234consolelog "Journo is previewing at "exec "open "
The best way to handle this bit seems to be entirely on the client-side. For
having the server spit out the slideshow code, simply have the blog detect
the list of images during page load and move them into a slideshow right then
and there -- using
alt attributes for captions, for example.
Since the blog is public, it's nice if search engines can see all of the pieces as well as readers.
We'll do the simplest possible command-line interface. If a public function
exists on the
Journo object, you can run it. Note that this lets you do
silly things, like
journo toString but no big deal.
= ->command = processargv2or 'preview'return do Journocommandif Journocommandconsoleerror "Journo doesn't know how to ''"
Let's also provide a help page that lists the available commands.
Journo.help = Journo'--help'= ->consolelog """Usage: journo [command]If called without a command, `journo` will preview your blog.init start a new blog in the current folderbuild build a static version of the blog into 'site'preview live preview the blog via a local serverpublish publish the blog to your remote server"""
And we might as well do the version number, for completeness' sake.
Journo.version = Journo'--version'= ->consolelog "Journo 0.0.1"
Little utility functions that are useful up above.
The file path to the source of a given
The server-side path to the HTML for a given
=name = postName postif name is 'index''site/index.html'else"site//index.html"
The name (or slug) of a post, taken from the filename.
= pathbasename post'.md'
The full, absolute URL for a published post.
Starting with the string contents of a post, detect the title -- the first heading.
=_findmarkedlexercontent tokentype is 'heading'?text
Starting with the string contents of a post, detect the description -- the first paragraph.
=desc = _findmarkedlexercontent tokentype is 'paragraph'?textmarkedparser markedlexer _template"..."renderVariablespost
Helper function to read in the contents of a folder, ignoring hidden files and directories.
=fsreaddirSyncfolderfilter fcharAt0 isnt '.'
Return the list of posts currently in the manifest, sorted by their date of publication.
= ->_sortBy _without_keyssharedmanifest'index.md'sharedmanifestpostpubtime
The shared variables we want to allow our templates (both posts, and layout) to use in their evaluations. In the future, it would be nice to determine exactly what best belongs here, and provide an easier way for the blog author to add functions to it.
=_fspathmapLinkpostNamefolderContentsposts: sortedPostspost: pathbasenamepostmanifest: sharedmanifest
Quick function which creates a link to a Google Map search for the name of the place.
=query = encodeURIComponent", ""<a href=\"&t=h&z=\"></a>"
Convenience function for catching errors (keeping the preview server from crashing while testing code), and printing them out.
=try do funccatch errconsoleerror errstack"<pre></pre>"
Finally, for errors that you want the app to die on -- things that should break the site build.
=consoleerror messageprocessexit 1