You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by pu...@apache.org on 2015/03/25 21:01:05 UTC

[2/2] cordova-browser git commit: CB-8182 port `cordova serve` to `cordova run browser`

CB-8182 port `cordova serve` to `cordova run browser`


Project: http://git-wip-us.apache.org/repos/asf/cordova-browser/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-browser/commit/57c6e3a6
Tree: http://git-wip-us.apache.org/repos/asf/cordova-browser/tree/57c6e3a6
Diff: http://git-wip-us.apache.org/repos/asf/cordova-browser/diff/57c6e3a6

Branch: refs/heads/master
Commit: 57c6e3a6de330aa877879f1b7988f7e664c4de2b
Parents: 3010832
Author: Tim Barham <ti...@microsoft.com>
Authored: Wed Mar 25 15:03:13 2015 +1000
Committer: Tim Barham <ti...@microsoft.com>
Committed: Wed Mar 25 15:03:13 2015 +1000

----------------------------------------------------------------------
 bin/templates/project/cordova/lib/run.js | 121 +++++++++++++++++++++++++-
 bin/templates/project/cordova/run        |  35 +++++---
 2 files changed, 142 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cordova-browser/blob/57c6e3a6/bin/templates/project/cordova/lib/run.js
----------------------------------------------------------------------
diff --git a/bin/templates/project/cordova/lib/run.js b/bin/templates/project/cordova/lib/run.js
index 83811aa..2022f89 100644
--- a/bin/templates/project/cordova/lib/run.js
+++ b/bin/templates/project/cordova/lib/run.js
@@ -1,8 +1,13 @@
 var spawn = require('child_process').spawn,
     shell = require('shelljs'),
     fs = require('fs'),
+    path = require('path'),
     exec = require('./exec'),
-    Q = require('q');
+    Q = require('q'),
+    http = require('http'),
+    url = require('url'),
+    mime = require('mime'),
+    zlib = require('zlib');
 
 /**
  * Launches the specified browser with the given URL.
@@ -46,11 +51,11 @@ exports.runBrowser = function (target, url) {
 }
 
 function mapTarget(target) {
-    var chromeArgs = ' --disable-web-security --user-data-dir=/tmp/temp_chrome_user_data_dir_for_cordova_browser';
+    var chromeArgs = ' --user-data-dir=/tmp/temp_chrome_user_data_dir_for_cordova_browser';
     var browsers = {
         'win32': {
             'ie': 'iexplore',
-            'chrome': 'chrome --disable-web-security --user-data-dir=C:/Chromedevsession',
+            'chrome': 'chrome --user-data-dir=C:/Chromedevsession',
             'safari': 'safari',
             'opera': 'opera',
             'firefox': 'firefox',
@@ -74,3 +79,113 @@ function mapTarget(target) {
     }
     return Q.reject("Browser target not supported: " + target);
 }
+
+function launchServer(projectRoot, port) {
+    var server = http.createServer( function(request, response) {
+        function do404() {
+            console.log('404 ' + request.url);
+            response.writeHead(404, {'Content-Type': 'text/plain'});
+            response.write('404 Not Found\n');
+            response.end();
+            return '';
+        }
+        function do302(where) {
+            console.log('302 ' + request.url);
+            response.setHeader('Location', where);
+            response.writeHead(302, {'Content-Type': 'text/plain'});
+            response.end();
+            return '';
+        }
+        function do304() {
+            console.log('304 ' + request.url);
+            response.writeHead(304, {'Content-Type': 'text/plain'});
+            response.end();
+            return '';
+        }
+        function isFileChanged(path) {
+            var mtime = fs.statSync(path).mtime,
+                itime = request.headers['if-modified-since'];
+            return !itime || new Date(mtime) > new Date(itime);
+        }
+
+        var urlPath = url.parse(request.url).pathname,
+            filePath = path.join(projectRoot, urlPath);
+
+        fs.exists(filePath, function(exists) {
+            if (!exists) {
+                return do404();
+            }
+            if (fs.statSync(filePath).isDirectory()) {
+                if (!/\/$/.test(urlPath)) {
+                    return do302(request.url + '/');
+                }
+                console.log('200 ' + request.url);
+                response.writeHead(200, {'Content-Type': 'text/html'});
+                response.write('<html><head><title>Directory listing of '+ urlPath + '</title></head>');
+                response.write('<h3>Items in this directory</h3>');
+                var items = fs.readdirSync(filePath);
+                response.write('<ul>');
+                for (var i in items) {
+                    var file = items[i];
+                    if (file) {
+                        response.write('<li><a href="'+file+'">'+file+'</a></li>\n');
+                    }
+                }
+                response.write('</ul>');
+                response.end();
+            } else if (!isFileChanged(filePath)) {
+                do304();
+            } else {
+                var mimeType = mime.lookup(filePath);
+                var respHeaders = {
+                    'Content-Type': mimeType
+                };
+                var readStream = fs.createReadStream(filePath);
+
+                var acceptEncoding = request.headers['accept-encoding'] || '';
+                if (acceptEncoding.match(/\bgzip\b/)) {
+                    respHeaders['content-encoding'] = 'gzip';
+                    readStream = readStream.pipe(zlib.createGzip());
+                } else if (acceptEncoding.match(/\bdeflate\b/)) {
+                    respHeaders['content-encoding'] = 'deflate';
+                    readStream = readStream.pipe(zlib.createDeflate());
+                }
+
+                var mtime = new Date(fs.statSync(filePath).mtime).toUTCString();
+                respHeaders['Last-Modified'] = mtime;
+                
+                console.log('200 ' + request.url + ', ' + mimeType + ', ' + mtime + ', ' + filePath);
+
+                response.writeHead(200, respHeaders);
+                readStream.pipe(response);
+            }
+            return '';
+        });
+    });
+
+    server.listen(port);
+
+    return server;
+}
+
+/**
+ * Launches a server of the specified path and returns the URL that will access the path.
+ * Based on subset of `cordova serve`
+ * @param  {string} path to serve over http
+ * @param  {number} port to serve http on
+ * @return {Q} Promise to URL that will access the path
+ */
+exports.runHttpServer = function (path, port) {
+
+    var server = launchServer(path, port),
+        urlRoot = 'http://localhost:' + port + '/',
+        deferred = Q.defer();
+
+    server.on('listening', function () {
+        deferred.resolve(urlRoot);
+    }).on('error', function (e) {
+        deferred.reject(e);
+    });
+
+    return deferred.promise;
+}

http://git-wip-us.apache.org/repos/asf/cordova-browser/blob/57c6e3a6/bin/templates/project/cordova/run
----------------------------------------------------------------------
diff --git a/bin/templates/project/cordova/run b/bin/templates/project/cordova/run
index 1c855c8..66ebc95 100755
--- a/bin/templates/project/cordova/run
+++ b/bin/templates/project/cordova/run
@@ -23,33 +23,46 @@ var shell = require('shelljs'),
     fs = require('fs'),
     path = require('path'),
     run = require('./lib/run'),
-    nopt  = require('nopt');
+    nopt  = require('nopt'),
+    url = require('url');
 
 var args = process.argv;
 
 start(args);
 
 function start(argv) {
-    var args  = nopt({'help': Boolean, 'target': String}, {'help': ['/?', '-h', 'help', '-help', '/help']}, argv);
+    var args  = nopt({'help': Boolean, 'target': String, 'port': Number}, {'help': ['/?', '-h', 'help', '-help', '/help']}, argv);
     if(args.help) {
         help();
     }
-    var configFile = path.resolve(path.join(path.join(__dirname, '../'), 'config.xml')),
+
+    // defaults
+    args.port = args.port || 8000;
+    args.target = args.target || "chrome";
+
+    var root = path.join(__dirname, '../'),
+        configFile = path.resolve(path.join(root, 'config.xml')),
         configXML = fs.readFileSync(configFile, 'utf8'),
-        sourceFile = /<content[\s\S]*?src\s*=\s*"(.*?)"/i.exec(configXML),
-        projectUrl = 'file://' + path.resolve(path.join(path.join(__dirname, '../'), 'www', sourceFile ? sourceFile[1] : 'index.html'));
+        sourceFile = /<content[\s]+?src\s*=\s*"(.*?)"/i.exec(configXML),
+        rootPlatform = path.resolve(path.join(root, 'www'));
+
+    run.runHttpServer(rootPlatform, args.port).then(function (urlRoot) {
+      var projectUrl = url.resolve(urlRoot, sourceFile ? sourceFile[1] : 'index.html');
+
+      console.log('Static file server running @ ' + projectUrl + '\nCTRL + C to shut down');
 
-    // Defaults to executing the chrome browser
-    run.runBrowser(args.target || "chrome", projectUrl).done();
+      return run.runBrowser(args.target, projectUrl);
+    }).done();
 }
 
 function help() {
-    console.log("\nUsage: run [ --target=<browser> ]");
-    console.log("    --target=<browser> : Launches the specified browser.");
+    console.log("\nUsage: run [ --target=<browser> ] [ --port=<number> ]");
+    console.log("    --target=<browser> : Launches the specified browser. Chrome is default.");
+    console.log("    --port=<number>    : Http server uses specified port numner.");
     console.log("Examples:");
     console.log("    run");
-    console.log("    run --target=ie");
-    console.log("    run --target=chrome");
+    console.log("    run -- --target=ie");
+    console.log("    run -- --target=chrome --port=8000");
     console.log("");
     process.exit(0);
 };


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cordova.apache.org
For additional commands, e-mail: commits-help@cordova.apache.org