Skip to content

Instantly share code, notes, and snippets.

@bergwerf
Created February 8, 2017 11:34
Show Gist options
  • Save bergwerf/ca3b68c29736c202802cb05a85421cbd to your computer and use it in GitHub Desktop.
Save bergwerf/ca3b68c29736c202802cb05a85421cbd to your computer and use it in GitHub Desktop.
PugJS for Dart by running a node process and communicating over stdio
// Copyright (c) 2017, Herman Bergwerf. All rights reserved.
// Use of this source code is governed by a MIT-style license.
import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:logging/logging.dart';
final log = new Logger('pug');
class PugRenderer {
Process process;
final queue = new List<Completer<String>>();
Future<Null> initialize(String template) async {
process = await Process.start('node', ['render.js', '$template.pug']);
process.stderr.listen((data) {
throw new Exception(
'Pug renderer experienced an error: ${UTF8.decode(data)}');
});
// Listen on stdout.
process.stdout.listen((data) {
log.info('Rendered Pug template');
queue.removeAt(0).complete(UTF8.decode(data));
});
}
Future<String> render(dynamic locals) {
log.info('Render Pug template');
final input = JSON.encode(locals);
final completer = new Completer<String>();
queue.add(completer);
process.stdin.writeln(input);
return completer.future;
}
}
// Copyright (c) 2017, Herman Bergwerf. All rights reserved.
// Use of this source code is governed by a MIT-style license.
var fs = require('fs')
var pug = require('pug')
var process = require('process')
var readline = require('readline')
var fileName = process.argv[2]
fs.readFile(fileName, (err, buf) => {
if (err) {
throw err
}
var str = buf.toString('utf8')
var fn = pug.compile(str)
// Start listening on stdin.
var lineReader = readline.createInterface({
input: process.openStdin()
})
lineReader.on('line', function (line) {
var json = JSON.parse(line)
process.stdout.write(fn(json))
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment