Node HTTP server
// Require what we need
var http = require("http");
// Build the server
var app = http.createServer(function(request, response) {
response.writeHead(200, {
"Content-Type": "text/plain"
});
response.end("Hello world!\n");
});
// Start that server, baby
app.listen(1337, "localhost");
console.log("Server running at http://localhost:1337/");
В браузере набрать
localhost:1337
localhost:1337/anime_currency
localhost:1337/?onlyfriend=anime
------------------------------------------------------------------------------
The request handler
var app = http.createServer(function(request, response) {
// Build the answer
var answer = "";
answer += "Request URL: " + request.url + "\n";
answer += "Request type: " + request.method + "\n";
answer += "Request headers: " + JSON.stringify(request.headers) + "\n";
// Send answer
response.writeHead(200, { "Content-Type": "text/plain" });
response.end(answer);
});
------------------------------------------------------------------------------
Add 404 Error page
var http = require("http");
http.createServer(function(req, res) {
// Homepage
if (req.url == "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("Welcome to the homepage!");
}
// About page
else if (req.url == "/about") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("Welcome to the about page!");
}
// 404'd!
else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 error! File not found.");
}
}).listen(1337, "localhost");
------------------------------------------------------------------------------
Connect
// Require the stuff we need
var connect = require("connect");
var http = require("http");
// Build the app
var app = connect();
// Add some middleware
app.use(function(request, response) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Hello world!\n");
});
// Start it up!
http.createServer(app).listen(1337);
------------------------------------------------------------------------------
Connect with Middleware
var connect = require("connect");
var http = require("http");
var app = connect();
// Logging middleware
app.use(function(request, response, next) {
console.log("In comes a " + request.method + " to " + request.url);
next();
});
// Send "hello world"
app.use(function(request, response) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Hello world!\n");
});
http.createServer(app).listen(1337);
------------------------------------------------------------------------------
Connect with Logger
var connect = require("connect");
var http = require("http");
var app = connect();
app.use(connect.logger());
// Fun fact: connect.logger() returns a function.
app.use(function(request, response) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Hello world!\n");
});
http.createServer(app).listen(1337);
Перейти в браузере на localhost:1337
------------------------------------------------------------------------------
Many pages with Connect
var connect = require("connect");
var http = require("http");
var app = connect();
app.use(connect.logger());
// Homepage
app.use(function(request, response, next) {
if (request.url == "/") {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the homepage!\n");
// The middleware stops here.
} else {
next();
}
});
// About page
app.use(function(request, response, next) {
if (request.url == "/about") {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the about page!\n");
// The middleware stops here.
} else {
next();
}
});
// 404'd!
app.use(function(request, response) {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("404 error!\n");
});
http.createServer(app).listen(1337);
------------------------------------------------------------------------------
Express
var express = require("express");
var http = require("http");
var app = express();
http.createServer(app).listen(1337);
------------------------------------------------------------------------------
Express Routing
var express = require("express");
var http = require("http");
var app = express();
app.all("*", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
next();
});
app.get("/", function(request, response) {
response.end("Welcome to the homepage!");
});
app.get("/about", function(request, response) {
response.end("Welcome to the about page!");
});
app.get("/hello/:who", function(req, res) {
res.end("Hello, " + req.params.who + ".");
// Fun fact: this has security issues
});
app.get("*", function(request, response) {
response.end("404!");
});
http.createServer(app).listen(1337);
Перейти в браузере на localhost:1337/hello/animelover69
------------------------------------------------------------------------------
Express Redirect
response.redirect("/hello/anime");
response.redirect("http://www.myanimelist.net");
response.redirect(301, "http://www.anime.org"); // HTTP status code 301
response.sendFile("/path/to/anime.mp4");
------------------------------------------------------------------------------
Express View
// Start Express
var express = require("express");
var app = express();
// Set the view directory to /views
app.set("views", __dirname + "/views");
// Let's use the Jade templating language
app.set("view engine", "jade");
app.get("/", function(request, response) {
response.render("index", { message: "I love anime" });
});
------------------------------------------------------------------------------
Connect and Node inside Express
var express = require("express");
var app = express();
app.use(express.logger()); // Inherited from Connect
app.get("/", function(req, res) {
res.send("anime");
});
app.listen(1337);
------------------------------------------------------------------------------
Read more on evanhahn.com/understanding-express-js/
четверг, 3 октября 2013 г.
JavaScript without jQuery
Selectors
Selecting by ID:
$('#foo')
document.getElementById('foo')
Selecting by class (not compatible with IE6-8, but good with everything else):
$('.bar')
document.getElementsByClassName('bar')
Selecting by tag name:
$('span')
document.getElementsByTagName('span')
Selecting sub-elements:
$('#foo span')
document.getElementById('foo').getElementsByTagName('span')
Selecting "special" elements:
$('html')
document.documentElement
$('head')
document.head
$('body')
document.body
Attributes
Getting/setting HTML:
$('#foo').html()
document.getElementById('foo').innerHTML
$('#foo').html('Hello, world!')
document.getElementById('foo').innerHTML = 'Hello, world!'
Dealing with classes:
$('#foo').addClass('bar')
document.getElementById('foo').className += ' bar '
$('#foo').removeClass('bar')
document.getElementById('foo').className = document.getElementById('foo').className.replace(/bar/gi, '')
$('#foo').hasClass('bar')
document.getElementById('foo').className.indexOf('bar') !== -1
Getting an input's value:
$('#foo').val()
document.getElementById('foo').value
Effects
Showing and hiding:
$('#foo').show()
document.getElementById('foo').style.display = ''
$('#foo').hide()
document.getElementById('foo').style.display = 'none'
Changing CSS:
$('#foo').css('background-color', 'red')
document.getElementById('foo').style.backgroundColor = 'red'
Events
Document ready
Do it the way MDN does it:
document.onreadystatechange = function() {
if (document.readyState === 'complete') {
// DOM is ready!
}
};
Second, use domReady, a tiny library that's used like this:
domready(function() {
// DOM is ready!
});
Clicks
$('#foo').click(function() { ... })
document.getElementById('foo').onclick = function() { ... }
Parsing JSON:
jQuery.parseJSON(json)
JSON.parse(json)
// The JSON object isn't in older browsers, so you can include it if it's not there.
// http://github.com/douglascrockford/JSON-js/blob/master/json2.js
Selecting by ID:
$('#foo')
document.getElementById('foo')
Selecting by class (not compatible with IE6-8, but good with everything else):
$('.bar')
document.getElementsByClassName('bar')
Selecting by tag name:
$('span')
document.getElementsByTagName('span')
Selecting sub-elements:
$('#foo span')
document.getElementById('foo').getElementsByTagName('span')
Selecting "special" elements:
$('html')
document.documentElement
$('head')
document.head
$('body')
document.body
Attributes
Getting/setting HTML:
$('#foo').html()
document.getElementById('foo').innerHTML
$('#foo').html('Hello, world!')
document.getElementById('foo').innerHTML = 'Hello, world!'
Dealing with classes:
$('#foo').addClass('bar')
document.getElementById('foo').className += ' bar '
$('#foo').removeClass('bar')
document.getElementById('foo').className = document.getElementById('foo').className.replace(/bar/gi, '')
$('#foo').hasClass('bar')
document.getElementById('foo').className.indexOf('bar') !== -1
Getting an input's value:
$('#foo').val()
document.getElementById('foo').value
Effects
Showing and hiding:
$('#foo').show()
document.getElementById('foo').style.display = ''
$('#foo').hide()
document.getElementById('foo').style.display = 'none'
Changing CSS:
$('#foo').css('background-color', 'red')
document.getElementById('foo').style.backgroundColor = 'red'
Events
Document ready
Do it the way MDN does it:
document.onreadystatechange = function() {
if (document.readyState === 'complete') {
// DOM is ready!
}
};
Second, use domReady, a tiny library that's used like this:
domready(function() {
// DOM is ready!
});
Clicks
$('#foo').click(function() { ... })
document.getElementById('foo').onclick = function() { ... }
Parsing JSON:
jQuery.parseJSON(json)
JSON.parse(json)
// The JSON object isn't in older browsers, so you can include it if it's not there.
// http://github.com/douglascrockford/JSON-js/blob/master/json2.js
понедельник, 30 сентября 2013 г.
array.indexOf() Bug fix for IE 6-8
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
'use strict';
if (this == null) {
throw new TypeError();
}
var n, k, t = Object(this),
len = t.length >>> 0;
if (len === 0) {
return -1;
}
n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
for (k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
'use strict';
if (this == null) {
throw new TypeError();
}
var n, k, t = Object(this),
len = t.length >>> 0;
if (len === 0) {
return -1;
}
n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
for (k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
четверг, 26 сентября 2013 г.
Используйте массивы вместо циклов for чтобы быстрее создать строку
var arr = ['item 1', 'item 2', 'item 3', ...];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';
Хитрый трюк временного удаления комментариев вида /* */
module = function(){
var current = null;
//*
var init = function(){
};
var show = function(){
current = 1;
};
var hide = function(){
show();
}
// */
return{init:init, show:show, current:current}
}();
var current = null;
//*
var init = function(){
};
var show = function(){
current = 1;
};
var hide = function(){
show();
}
// */
return{init:init, show:show, current:current}
}();
Пишите код внутри модулей
module = function(){
var current = null;
var labels = {
'home':'home',
'articles':'articles',
'contact':'contact'
};
var init = function(){
};
var show = function(){
current = 1;
};
var hide = function(){
show();
}
return{init:init, show:show, current:current}
}();
module.init();
var current = null;
var labels = {
'home':'home',
'articles':'articles',
'contact':'contact'
};
var init = function(){
};
var show = function(){
current = 1;
};
var hide = function(){
show();
}
return{init:init, show:show, current:current}
}();
module.init();
Выбрать все тэги на странице через символ *
var allTagsOnThePage = document.getElementsByTagName('*');
console.log(allTagsOnThePage.length);
console.log(allTagsOnThePage.length);
Подписаться на:
Сообщения (Atom)