Skip to content

Instantly share code, notes, and snippets.

@kevyworks
Created March 16, 2014 13:38
Show Gist options
  • Save kevyworks/9583382 to your computer and use it in GitHub Desktop.
Save kevyworks/9583382 to your computer and use it in GitHub Desktop.
Node Main
// node-main.js
"use strict";
var _ = require("lodash"),
path = require("path"),
co = require("co"),
fs = require("co-fs"),
Queue = require("co-queue"),
cwd = process.cwd(),
appdir = path.join(cwd, 'app'),
winObject = null;
process.on('uncaughtException', function(e) {
log().error(e);
});
function log() {
return getWindow().console;
}
function *getPackage() {
var pkg = yield fs.readFile(path.join(cwd, "package.json"), "utf8");
return JSON.parse(pkg);
}
function *importJS(src) {
try {
var head = getWindow().document.getElementsByTagName("head")[0],
raw = getWindow().document.createElement("script"),
src_path = path.join(appdir, src);
if (yield fs.exists(src_path)) {
log().info("LOADING `" + src_path + "`");
var source = yield fs.readFile(src_path, "utf8");
raw.appendChild(getWindow().document.createTextNode(source));
head.appendChild(raw);
head.removeChild(raw);
} else {
log().warn("Failed to importJS `" + src_path + "`");
}
} catch (e) {
log().error("Unable to importJS `" + src_path + "` >> " + JSON.stringify(e));
}
}
function *importScripts(s) {
for (var i = 0; i < s.length; i++) {
yield importJS(s[i]);
}
}
function getWindow() {
if (winObject === null) {
return window;
} else {
return winObject;
}
}
exports.setWindowObject = function(w) {
winObject = w;
};
exports.init = function(cb) {
co(function *() {
var pkg = yield getPackage();
// load scripts
yield importScripts(pkg.configs.libraries);
if (_.isFunction(cb)) cb();
})();
};
// usage in package.json:
{
...
...
"node-main": "node-main.js",
"configs": {
"libraries": [
"resources/thirdparty/jquery/jquery.js",
"resources/thirdparty/bootstrap/bootstrap.js",
"resources/thirdparty/mousetrap/mousetrap.js",
"resources/thirdparty/mousetrap/plugins/bind-dictionary/main.js",
"resources/thirdparty/mousetrap/plugins/global-bind/main.js",
"resources/thirdparty/less/less.js",
"main.js"
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment