Мой первый Node.js-пакет
Apr. 30th, 2012 02:35 pmОпубликовал свой первый пакет на свалке Node.js. Теперь запустить пример с «Hello World!», который будет доступен по локальному адресу, можно следующим образом:
alexo@codedot:/tmp$ npm install uniweb npm http GET https://registry.npmjs.org/uniweb npm http 200 https://registry.npmjs.org/uniweb npm http GET https://registry.npmjs.org/ws npm http 304 https://registry.npmjs.org/ws > ws@0.4.13 preinstall /private/tmp/node_modules/uniweb/node_modules/ws > make node-waf configure build Checking for program g++ or c++ : /usr/bin/g++ Checking for program cpp : /usr/bin/cpp Checking for program ar : /usr/bin/ar Checking for program ranlib : /usr/bin/ranlib Checking for g++ : ok Checking for node path : ok /usr/local/lib/node_modules Checking for node prefix : ok /usr/local 'configure' finished successfully (0.183s) Waf: Entering directory `/private/tmp/node_modules/uniweb/node_modules/ws/build' [1/4] cxx: src/validation.cc -> build/Release/src/validation_1.o [2/4] cxx: src/bufferutil.cc -> build/Release/src/bufferutil_2.o [3/4] cxx_link: build/Release/src/validation_1.o -> build/Release/validation.node [4/4] cxx_link: build/Release/src/bufferutil_2.o -> build/Release/bufferutil.node Waf: Leaving directory `/private/tmp/node_modules/uniweb/node_modules/ws/build' 'build' finished successfully (1.050s) npm http GET https://registry.npmjs.org/commander npm http GET https://registry.npmjs.org/options npm http 304 https://registry.npmjs.org/commander npm http 304 https://registry.npmjs.org/options uniweb@1.1.1 ./node_modules/uniweb └── ws@0.4.13 (options@0.0.3, commander@0.5.2) alexo@codedot:/tmp$ npm test uniweb > uniweb@1.1.1 test /private/tmp/node_modules/uniweb > node hello.js
Не считая примера, код пакета занимает всего 62 строки. Ниже комбинированный HTTP/HTTPS/WebSocket-сервер на его основе, который работает под рутом, так как использует порты 80 и 443, и ожидает SSL-сертификат в файлах key.pem
и cert.pem
:
var start = require("uniweb"); var read = require("fs").readFileSync; function hello(socket) { socket.on("message", function(msg) { socket.send("alert(\"" + msg + "\");"); }); socket.send("socket.send(\"Hello World!\");"); } start({ handler: hello, domain: "example.com", key: read("key.pem"), cert: read("cert.pem") });