$ sudo apt-get install nodejs
$ node file.js
var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World\n'); }).listen(3000); console.log('Server running at http://127.0.0.1:3000/');
$ node server.js
array.forEach()
, JSON, getters/setters, freeze/seal, and more...document
object. (There are libraries for that though...)./node-web-boilerplate/
node_modules/
- automatically managed by NPM
package.json
- tells NPM what to do
config/
- .js files that configure things
scripts/
- place for helper scripts, githook scripts
Makefile
- automates much for us
public/
- static files, publicly available via HTTP
views/
- dynamic template files for HTML views
server.js
- main code file for our node.js server
app/
- place for additional server-side .js code
package.json
// ... "dependencies": { "express": "2.5.11", // node.js web application framework "underscore": "1.4.1", // JS helper lib "swig": ">= 0.12.0" // django-like HTML templates }, "devDependencies": { "nodelint": "0.6.2", // linting "nodeunit": "0.7.4" // unit tests }, // ...
$ npm install -d
./node_modules
./config/config-lint.js
./Makefile
, but you could use a shell script or whatever$ make all
npm install -d
for usmake all
again, coming full circle...var express = require('express'), config = require('./config/config-app'), app = express.createServer(); app.use(express.static(config.public)); app.listen(3000);
require('module-name')
require('./path/file-name')
module.exports
./server.js
./public/js/
./app/
./public/shared/
./public/
// Node.js server code var MyObject = require('./public/shared/MyObject'); // Browser code <script src="/shared/MyObject.js"></script>
require()
or module.exports
MyObject.js
(function () { var nodejs = (typeof module !== 'undefined' && module.hasOwnProperty('exports')), _ = nodejs ? require('underscore') : window._; // Browser code will need to load underscore.js function MyObject() { this.hello = 'world'; } if (nodejs) { module.exports = MyObject; } else { window.MyObject = MyObject; } }());
var express = require('express'), config = require('./config/config-app'), app = express.createServer(), io = require('socket.io').listen(app); app.use(express.static(config.public)); app.listen(3000); // Socket.io code uncoupled from HTTP server!! io.sockets.on('connection', function (socket) { socket.emit('news', {hello: 'world'}); });
.listen(app)
command on server<html> <body> <p>news.hello = <span id="test"></span></p> <!-- This folder is not in ./public/. The URL is automatic. --> <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); socket.on('news', function (data) { document.getElementById('test').innerHTML = data.hello; }); </script> </body> </html>