looking for a full-immersion/face-to-face HTML5, JavaScript, and Mobile Web Development training in the heart of London? Book your spot
Showing posts with label server. Show all posts
Showing posts with label server. Show all posts

Wednesday, July 11, 2012

(က) Polpetta, any folder is served spiced

The quick version is: have you ever thought about using node.js to make any folder as a web-server and in a PHPish way where .njs files are required and executed runtime as node modules ?

Oh well, I did, and this is the result in Github: polpetta ... enjoy!

Wednesday, August 24, 2011

Simulate Script Injection Via Data URI

Well, not only downloads on the fly, the data uri works for almost everything ( only iOS 5 beta does not want to work with inline data uri AUDIO sources .... but this is another story ... ) ... so ...

How To Simulate Script injection

Let's say you want a test but you don't want to bother a server. However, you want to be sure the test is asynchronous and it simulates the server.

var
head = document.getElementsByTagName("head")[0],
script = document.createElement("script")
;
head.insertBefore(script, head.lastChild);
script.src = "data:text/javascript;base64," + btoa(
"alert('Hello World')"
);


How To Simulate JSONP

Same trick, isn't it? ... except:

script.src = "data:text/javascript;base64," + btoa(
"callback(" + JSON.stringify(dummyData) + ")"
);


How To Drop Server Requests

well, this is the tricky one ...

Surely there is some job to do in the createResponse() function but ... hey, we can stop bothering servers now ;)

Thursday, August 18, 2011

HTML5: How To Create Downloads On The Fly

this is a quick one I have implemented already in fuckn.es in the create angry memory button logic ...

The New Download Attribute

Hopefully soon, most updated browser will implement the download attribute in hypertext links (aka: <a> tag)
The quick summary is this one:
The download attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. The attribute may have a value; the value, if any, specifies the default filename that the author recommends for use in labeling the resource in a local file system.

And this is a basic example:
click here to
<a
    href="resource234.txt"
    download="license.txt"
>
    download the license
</a>


What Is Download For

Well, I am pretty sure you have read at least once in your life this kind of extra info beside a link:
right click to download the content and "Save As ..."
Moreover, I am pretty sure you have created at least once in your server a page able to force a generic file download.
All these instructions and server side headers/files may disappear thanks to this new attribute, also because there's no such thing as "right button" on touch screens, neither in some newer device pointer.
If the file is meant to be download, it will ... cool?

Create Downloads On The Fly Via JavaScript

When I have read about it, I have instantly realized the potentials of this attribute combined with inline data uri scheme.

Only HTML5 ?

Nope! Please note that many browsers let us already practice this technique. Some may open the file in a new blank page while some other may download directly the file as is for Chrome and the CSV example.
As graceful degradation, the "right click" procedure will still do the trick.

Downlaod Canvas As Image Example

First example is a classic one: how to save a canvas snapshot as image via "click".
// basic example
function createDownloadLink(canvas, name) {
    var a = document.createElement("a");
    a.download = name;
    a.title = "download snapshot";
    a.href = canvas.toDataURL();
    return a;
}

// some paragraph in the page
document.querySelector(
    "p.snapshot"
).appendChild(createDownloadLink(
    document.querySelector("#game"),
    "snapshot" + (-new Date) + ".png"
));

When the user will tap/click on the link, the browser will simply start the download. No server side involved at all!

Save A Page As PDF

Thanks to this technique we may use same trick to produce a PDF file out of whatever web page.
// basic example
function createPDFLink(fileName) {
    var doc = new pdf();
    // whatever content you want to download
    var a = document.createElement("a");
    a.download = fileName;
    a.title = "download as PDF";
    a.href = doc.output('datauri',{"fileName":name});
    return a;
}

// some paragraph in the page
document.querySelector(
    "p.saveaspdf"
).appendChild(createPDFLink(
    "document-" + document.title + ".pdf"
));

Of course if the page content changes we can replace the old link with a freshly new created one.

Save Table As CSV

Well, another classic here, the csv format out of a table. This is a basic but working example ;)
<script>
// really basic example
function tableToCSV(table) {
    for (var
        header = table.querySelectorAll("tr th"),
        rows = table.querySelectorAll("tr td"),
        hlength = header.length,
        length = hlength + rows.length,
        result = Array(hlength),
        i = hlength,
        j;
        i < length; ++i
    ) {
        j = i % hlength;
        j || result.push("\n");
        result.push(rows[j].innerHTML);
        ++j % hlength && result.push(",");
    }
    i = 0;
    while (i < hlength) {
        result[i] = header[i].innerHTML + (
            ++i < hlength ? "," : ""
        );
    }
    return result.join("");
}
this.onload = function () {
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "table.csv";
    a.href = "data:text/csv;base64," + btoa(
        tableToCSV(document.querySelector("table"))
    );
    a.innerHTML = "download csv";
};
</script>
<table>
    <tr>
        <th>name</th>
        <th>age</th>
    </tr>
    <tr>
        <td>Dan</td>
        <td>33</td>
    </tr>
    <tr>
        <td>John</td>
        <td>32</td>
    </tr>
</table>

Most likely we can test already above example even if the name won't probably be the chosen one.
For safe base64 encode, compatible with UTF-8 pages, have a look at this script ( base64.encode() and base64.decode() ).


Different developers asked already about compatibility.
As I have said before, we need to differentiate between "download" attribute compatibility AND inline data uri link compatibility.
In the first case I don't know browsers that will force the download with the specified name yet, but I'll update this section as soon as I know someone.
In the latter case, IE9, Chrome, Firefox, Safari, Webkit based, and Opera seem to be already compatible.
The main problem/limit I have spotted in fuckn.es is the size of the data uri, in certain cases we may need a decent/fast machine otherwise we may end up killing RAM and CPU performances.
IE8 is compatible as well except IE8 has limited data uri for CSS images, as example, and I expect same limit for this technique.
Bear in mind when all browsers will be compatible, we will still have data stream limit problem, or better, really big files has to be parsed on the fly in one shot, no "download progress" possibility.


As Summary

... now you know ... ;)

Monday, February 01, 2010

CommonJS - Why Server Side Only?

There is one single thing I don't like about CommonJS Idea, the fact nobody is thinking about the client side!!!

CommonJS Why

Since everybody would like to use JavaScript as Server Side Programing Language, where right now I can count there about 50 implementations, somebody decided that at least basic stuff such IO operations, streams or sockets, and much more, should have a common behavior, namespace, API, across all different implementations.
In few words, these guys are trying to create their own WSW Consortium, and this is absolutely OK.
So what am I complaining about?

Client CommonJS

If we, as developers and libraries authors, would have adopted a similar strategy ages ago, rather than fight with each other about natives prototypes pollutions, web development would be probably even easier for everybody.
We failed, while those server side guys started correctly.
The problem, for both language usage and its environment, is that JavaScript on server has different problems than a bloody "attachEvent VS addEventListener" but while common practices are in any case appreciated and widely adopted world wide, CommonJS is not friendly at all with Client Side JavaScript.
The basic example?

require

This function aim is to retrieve from a namespace, where it is basically represented via dot notation, translated into folders paths, a generic variable, object, function, whatever.
The power a dedicated build could have over ouw miserable secured/sandboxed version of browser JavaScript engines is endless.
As example, the only way I could think about to implement a client side require, is this one:

if (typeof require === "undefined") {
// (C) WebReflection - Mit Style License
var require = (function (context, root, Function) {
function require(namespace) {
if (!hasOwnProperty.call(cache, namespace)) {
var xhr = new XMLHttpRequest;
xhr.open("GET", (root + "." + namespace.replace(/(^.*)(?:\.[0-9A-Za-z$_]+)$/, "$1")).replace(/\./g, "/") + ".js", false);
xhr.send(null);
cache[namespace] = Function(xhr.responseText + ";return function(){return eval(arguments[0])};").call(context);
}
return /(?:^.*\.|^)([0-9A-Za-z$_]+)$/.test(namespace) && cache[namespace](RegExp.$1);
};
var XMLHttpRequest = this.XMLHttpRequest || function () {
return new ActiveXObject("Microsoft.XMLHTTP");
};
var cache = {};
var hasOwnProperty = cache.hasOwnProperty;
return require;
})(this, "", this.Function);
}


How It Works

Let's say we have a file called mylib.js and let's say this file contains our libraries variables.
To obtain the base object, we could simply do something like this:

<script src="require.js"></script>
<script>
var base = require("mylib.base");
base.alert("hello");

var $alert = require("mylib.base").alert;
$alert("world");
</script>

Where mylib.js file is nothing different from:

var base = (function () {
var self = this;
return {
alert:function (msg) {
self.alert(msg);
}
};
}).call(this);

Easy? In few words if a file contains proper variable declarations, rather than global myvar = {} without var prefix, we can imagine we could have all our libraries automatically "sandboxed", at least the global namespace won't be polluted that much and via my implementation of require, each file will be loaded simply once and never again, and we can retrieve step after step just what we need.

P.S. please note that my implementation is just an imperfect proof of concept since require in CommonJS accepts syntax like require("mylib").base; but untile we won't have runtime cross browser resolved get/set, this is not possible to implement synchronously :(

Wednesday, February 20, 2008

packed.it goes off line !

... or, to be honest, that's what it's gonna do in few days, but PHP version is out!

You can find every information about server side version of packed it directly in this page.

I am not joking when I said that packed.it is probably the fastest optimized client files server you can find over the net, even with an uncompiled program language like PHP.

The key is the JOT compiler, compile one time, serve all the time without paranoia, saving bandwidth for both server and client, avoiding the usage of gz handlers, avoiding runtime compression, avoiding whathever you want, and finally, having the possibility to serve js, css, or both with a single file.

Discover by yourself how long server need to serve, for example, jQuery ... less than one millisecond without louds of requests ... please look at X-Served-In header, if you do not trust me :P

What's new? You do not need to pass in packed.it site to compile your projects, you can just serve and compile them directly from your one.

To Do:
Python PSP and SWGI version, C# version and finally, Jaxter version for server side JavaScript auto compilation in itself language ... does it sound good?

Enjoy packed.it, and please do not ignore totally PayPal Donation :D

Cheers