$ git clone https://github.com/rileyhilliard/usc-lecture.git usc-node-demo
$ cd usc-node-demo/node-server
nodejs.org
// server.js
console.log('Helo World!');
console.log('This was logged from the node.js server');
$ node server.js
$ node hello.js
HTTP Module
// hello.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
console.log("I am going to write 'Hello World'");
res.end('Hello World\n');
console.log("I wrote 'Hello World'");
}).listen(3000);
console.log('Server running at http://localhost:3000/');
$ node async.js
// async.js
var http = require('http');
var counter = 0;
var isThisLast = function(message){
console.log('3 - isThisLast\'s message is: '+message);
};
var doThisFunction = function(res, func){
setTimeout(function(){
console.log('4 - doing doThisFunction');
},3000)
func("What's Up Last function being called?!");
};
var seconds = function(){
var seconds = 0;
var plural = "";
setInterval(function(){
seconds++;
plural = (seconds > 1 ? "s" : "");
console.log("It's been "+seconds+" second"+plural+"\n");
},1000)
};
var doAnotherThing = function(res){
console.log('2 - doing ANOTHER thing');
doThisFunction(res, isThisLast);
};
http.createServer(function (req, res) {
counter++;
res.writeHead(200, {'Content-Type': 'text/plain'});
setTimeout(function(){
doAnotherThing(res);
}, 0);
console.log('1 - == END OF STACK == Ran this thing '+counter+' times')
res.end('Hello World\n');
}).listen(3000);
seconds();
console.log('Server running at http://localhost:3000/');
$ node file.js
//file.js
var http = require('http');
var fs = require('fs');
var message = "This is the Message that is going";
message += "to be written to a file";
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
fs.writeFile("test.txt", message, function(err) {
if(err) {
res.end(err);
} else {
console.log("The file was saved!");
res.end('The file was saved!\n');
}
});
}).listen(3000);
console.log('Server running at http://localhost:3000/');
more on this later...