Created
December 24, 2016 11:49
-
-
Save cubehouse/329849c07f06b6ee868e26744b9908f3 to your computer and use it in GitHub Desktop.
Factorio BluePrint String Parser in NodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var input = `H4sIAAAAAAAA/42R0WrDMAxFfyX0OYImg74Uf0vxbK0V2HImOWHD5N/ndKOsacn2FAjn5lzd+NSE5G | |
xoTqYgZ8qEakphG9HsrCrG10B8hmjdhRih37VD0oolNuXDwEv7afbz3P4kNFrJQKwoGWXFdle29STo | |
ri8Pt1xIZ9JMDtwFNcNQzTQhDJIm8usP7e+df7dclYzoaYyAodaQ6hxSwPvA0hS6/531cFV/i71Z3R | |
yjex5bjSH4PtbnsxV+VdxwPagONUYu8fKniT0uyMaW1fFN9ZvUPB8F8yjcnI7I/gvQdo5aWgIAAA==`; | |
var crypto = require("crypto"); | |
var zlib = require("zlib"); | |
var LuaVMJS = require('lua.vm.js'); | |
// create our luaVM for re-use | |
var luaVM = new LuaVMJS.Lua.State(); | |
// load our modified JSON lib that pushes JSON to global scope | |
luaVM.execute(require("fs").readFileSync(__dirname + "/json.lua", "utf-8")); | |
function Decode(str) { | |
return new Promise(function(resolve, reject) { | |
zlib.unzip(Buffer.from(str, 'base64'), (err, buffer) => { | |
if (!err) { | |
return resolve(buffer.toString()); | |
} else { | |
// handle error | |
reject(err); | |
} | |
}); | |
}); | |
} | |
function Parse(str) { | |
return new Promise(function(resolve, reject) { | |
// create variable name we want lua to inject into | |
var injectVar = "factorio_bp_" + RandomString(64); | |
// turn Blueprint string into a function | |
// TODO - OMG HOW DO I CHECK THIS IS SAFE TO DO??? | |
luaVM.execute(` | |
function export_bp_${injectVar}() | |
${str} | |
end`); | |
// inject LUA table as JSON into JS global variable | |
luaVM.execute(` | |
js.global.${injectVar} = JSON:encode(export_bp_${injectVar}()) | |
`); | |
// return a JSON parsed version of the injected string | |
resolve(JSON.parse(global[injectVar])); | |
// remove export_bp_${injectvar} function | |
luaVM.execute(` | |
export_bp_${injectVar} = nil | |
`); | |
// delete from the JS global scope too to clear up memory | |
delete global[injectVar]; | |
}); | |
} | |
// generate a random string for lua->js variable injection | |
function RandomString(len) | |
{ | |
return crypto.randomBytes(len).toString('hex'); | |
} | |
Decode(input).then(Parse).then(function(data) { | |
console.log(JSON.stringify(data, null, 2)); | |
}, console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment