Created
May 11, 2012 04:35
-
-
Save euforic/2657541 to your computer and use it in GitHub Desktop.
Quick dirty hack for Node.js like modules with package.json and node_module directory for Titanium
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
require('require_patch')(this); | |
/** | |
* Loads "myModule" from your applications "Resources/titan_modules" directory if package.json is present. | |
* If "main" is set in package.json module will be loaded from that file else defaults to "index.js" | |
*/ | |
var myModule = require('myModule'); | |
myModule.someFunction(); |
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
{ | |
"author": "Christian Sullivan <cs[at]euforic.co> (http://roguesynaptics.com)", | |
"name": "myModule", | |
"description": "My Awesome Module", | |
"version": "0.0.1", | |
"homepage": "http://gist.github.com/2657541", | |
"repository": { | |
"type": "git", | |
"url": "git://gist.github.com/2657541.git" | |
}, | |
"dependencies": {}, | |
"devDependencies": {}, | |
"optionalDependencies": {}, | |
"engines": { | |
"titanium": "2.0.1" | |
} | |
} |
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 RES_DIR = Titanium.Filesystem.resourcesDirectory; | |
var MOD_DIR = 'titan_modules/'; | |
/** | |
* get File | |
* Check if file exists and return its content | |
*/ | |
function getFile(file) { | |
var _file = Ti.Filesystem.getFile(file); | |
var fileExists = _file.exists(); | |
return { | |
exists: fileExists | |
, content: ((fileExists) ? _file.read().text : '') | |
}; | |
} | |
/** | |
* getPackageJSON | |
* Gets package.json file and returns is content as a JSON object | |
*/ | |
function getPackageJSON(module) { | |
var pkg = getFile(RES_DIR+'/titan_modules/'+module+'/package.json'); | |
return (pkg.exists) ? JSON.parse(pkg.content) : module; | |
}; | |
/** | |
* resolvePath | |
* Resolve path of module | |
*/ | |
function resolvePath(module) { | |
var _path = getPackageJSON(module); | |
return ('object' === typeof _path) ? MOD_DIR+module+'/'+(_path.main||'index.js').replace('.js', '') : module; | |
} | |
/** | |
* modified require function | |
*/ | |
module.exports = function(object) { | |
old_require = object.require; | |
object.require = function(module) { | |
return old_require(resolvePath(module)); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment