Last Updated: February 25, 2016
·
451
· samharnack

Titanium Module NPM Post Install

Turn your Titanium module project into an NPM package and add the following script to your package json.

"scripts": {
  "postinstall" : "node scripts/postinstall"
}

Then, in your "scripts" folder, add the following and name it "postinstall.js".

var fs = require("fs");
var zipMatcher = /^([^-]*)-([^-]*)-([^-]*)\.zip$/;
var moduleTemplate = "\t<module platform=\"$2\" version=\"$3\">$1</module>";
var moduleFolder = process.env.PWD;
var projectFolder = moduleFolder.slice(0, Math.max(0, moduleFolder.indexOf("/node_modules")));

if ("" !== projectFolder) {
  fs.readdir("./", function (error, files) {
    var zipfiles = files.filter(function (file) {
      return zipMatcher.test(file);
    });

    zipfiles.forEach(function (file) {
      var src = [ moduleFolder, file ].join("/"),
        dest = [ projectFolder, file ].join("/");

      fs.createReadStream(src)
        .pipe(fs.createWriteStream(dest));

      console.log("Installed {dest}"
        .replace("{dest}", file)
      );

      console.log("Don't forget to add the module to your tiapp.xml");
      console.log(file.replace(zipMatcher, moduleTemplate));
    });
  });
}