UNPKG

gourmet-generator

Version:

Code generator using Javascript scripts and mustache templates

81 lines (64 loc) 2.05 kB
var fs = require('fs') var path = require('path') var mustache = require('mustache') // base is the folder where the tt script is located // all file stuff are related to this base path var Runner = module.exports.Runner = function() { this.scriptPath = null; this.base = null; this.script = null; } Runner.prototype.load = function(scriptPath) { this.scriptPath = scriptPath; this.base = path.dirname(scriptPath); this.script = fs.readFileSync(scriptPath, 'utf8'); } var API = { __base: null, args: null, write: function(filePath, text) { var fp = path.join(API.__base, filePath) fs.writeFileSync(fp, text, 'utf8'); }, read: function(filePath) { var fp = path.join(API.__base, filePath) var result = fs.readFileSync(fp, 'utf8'); return result; }, mustache: function(template, values) { var output = mustache.render(template, values); return output; }, init: function(filePath, args) { var fp = path.join(API.__base, filePath) var runner = new Runner(); runner.load(fp); var result = runner.execute(args); return result; } } Runner.prototype.execute = function(args) { console.log('--- ---') console.log('--- --- Starting runner execute') console.log('--- --- path:' + this.scriptPath) console.log('--- --- base: ' + this.base) console.log('--- --- args: ' + args) console.log('--- --- script: ' + this.script) console.log('--- ---\n') var container = '\nfunction execute () {\n' + this.script + '\n}\n\n result = execute();\n' var self = this; // result is updated inside eval var result = null; function context () { 'use strict' // put the API on the eval context with name tt var tt = API; // update the folder of the tt script being executed tt.__base = self.base; // add the arguments (used when this script is being started by another script) tt.args = args; eval(container); } context(); return result; }