Маленькая библиотека для получения данных сайта в стиле jQuery AJAX.
Файл init.js
var request = require('./request');
var cheerio = require('cheerio');
var data = JSON.stringify({
'key1': 'value1'
, 'key2': 'value2'
});
request.httpRequest({
host: 'www.google.com'
, port: 80
, url: '/'
, type: 'POST'
, headers: {
'Content-Type': 'application/x-www-form-urlencoded'
, 'Content-Length': data.length
}
, data: data
, timeout: 120000
, success: function (data) {
var $ = cheerio.load(data);
console.log('Request body text inside <p></p>: ' + $('p').first().text());
}
, error: function (error) {console.log('New request error');}
});
Файл request.js
var http = require('http');
function randomNumber (min, max) {
min = parseInt(min, 10);
max = parseInt(max, 10);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var commonHeaders = {
'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.' + randomNumber(2, 5)
, 'Accept-Language': 'en-us,en;q=0.' + randomNumber(5, 9)
, 'Accept-Charset': 'utf-8,windows-1251;q=0.7,*;q=0.' + randomNumber(5, 7)
, 'Keep-Alive': '300'
, 'Expect': ''
};
function httpRequest (options) {
if (!options.hasOwnProperty('host')) {options.host = 'localhost';}
if (!options.hasOwnProperty('port')) {options.port = 80;}
if (!options.hasOwnProperty('url')) {options.url = '/';}
if (!options.hasOwnProperty('type')) {options.type = 'GET';}
if (!options.hasOwnProperty('headers')) {options.headers = {};}
if (!options.hasOwnProperty('data')) {options.data = {};}
if (!options.hasOwnProperty('timeout')) {options.timeout = 120000;}
if (!options.hasOwnProperty('success')) {options.success = function(){};}
if (!options.hasOwnProperty('error')) {options.error = function(error){console.log('Request error: ' + error);};}
for (var key in options.headers) {
commonHeaders[key] = options.headers[key];
}
var requestOptions = {
hostname: options.host
, port: options.port
, path: options.url
, method: options.type
, headers: options.headers
};
var request = http.request(requestOptions, function(response) {
console.log('Response status code: ' + response.statusCode);
console.log('Response header: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
var data = '';
response.on('data', function(chunk){data += chunk;});
response.on('end', function(){options.success(data);});
});
request.setTimeout(options.timeout, function(){console.log('Request timeout');});
request.on('error', options.error);
if (options.data.length > 0) {request.write(options.data);}
request.end();
}
exports.httpRequest = httpRequest;
Пример запуска кода в консоли командной строки
node init.js
Пример полного взаимодействия клиента и сервера на Node JS.
Файл client.js
var http = require('http');
var postData = JSON.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: '127.0.0.1',
port: 80,
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var request = http.request(options, function(response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
request.on('error', function(error) {
console.log('problem with request: ' + error.message);
});
// write data to request body
request.write(postData);
request.end(); // Always need to write request.end();
Файл server.js
var server = require("./export");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
handle["/show"] = requestHandlers.show;
server.start(router.route, handle);
Файл export.js
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
/*
var postData = "";
request.setEncoding("utf8");
request.addListener("data", function(postDataChunk) {
postData += postDataChunk;
console.log("Received POST data chunk '"+
postDataChunk + "'.");
});
request.addListener("end", function() {
route(handle, pathname, response, postData);
});
*/
route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(80);
console.log("Server has started.");
}
exports.start = start;
Файл router.js
function route(handle, pathname, response, request/*postData*/) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response, request/*postData*/);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
Файл requestHandler.js
var querystring = require("querystring"),
fs = require("fs"),
formidable = require("formidable");
function start(response) {
console.log("Request handler 'start' was called.");
var body = '<html>'+
'<head>'+
'<meta http-equiv="Content-Type" '+
'content="text/html; charset=UTF-8" />'+
'</head>'+
'<body>'+
'<form action="/upload" enctype="multipart/form-data" '+
'method="post">'+
'<input type="file" name="upload" multiple="multiple">'+
'<input type="submit" value="Upload file" />'+
'</form>'+
'</body>'+
'</html>';
response.writeHead(200, {"Content-Type": "text/html"});
response.write(body);
response.end();
}
function upload(response, request) {
console.log("Request handler 'upload' was called.");
var form = new formidable.IncomingForm();
console.log("about to parse");
form.parse(request, function(error, fields, files) {
console.log("parsing done");
/* Возможна ошибка в Windows: попытка переименования уже существующего файла */
fs.rename(files.upload.path, "/tmp/test.png", function(err) {
if (err) {
fs.unlink("/tmp/test.png");
fs.rename(files.upload.path, "/tmp/test.png");
}
});
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:<br/>");
response.write("<img src='/show' />");
response.end();
});
}
function show(response) {
console.log("Request handler 'show' was called.");
fs.readFile("/tmp/test.png", "binary", function(error, file) {
if(error) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(error + "\n");
response.end();
} else {
response.writeHead(200, {"Content-Type": "image/png"});
response.write(file, "binary");
response.end();
}
});
}
exports.start = start;
exports.upload = upload;
exports.show = show;
Пример запуска кода сервера в консоли командной строки
node server.js
Пример запуска кода клиента в консоли командной строки
node client.js
круть.
ОтветитьУдалитьнедавно в качестве рандомМинМакс заюзил это.
function mm(min, max) {
return (Math.random()*max)+min|0;
}
Приятнота и покороче (помню на javascript.ru разводили беседы на тему этой функии http://learn.javascript.ru/task/sluchajnoe-celoe-ot-min-do-max )