Node(2) First Code

you can use a command line prompt to do node

meta-commands

.help shows help menu

.clear wipes out variables


Hello World

//include http library into the program
//http object has the http library functionality
var http = require( 'http' );

//unlike php, you have to create the server
//listen to port 8124
http.createServer( function(req, res){
	//set http response header
	res.writeHead(200, { 'Content-Type': 'text/plain'});
	res.write( 'Hello' );
	res.end( ' World\n');
}).listen(8124, "127.0.0.1" );

//print a message to stdout
console.log( 'Server running at http://127.0,0.1:8124/');

http.createServer([requestListener])

Returns a new web server object.

requestListener is optional and added to request event

response functions

response.writeHead(statusCode, [reasonPhrase], [headers])

Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable reasonPhrase as the second argument.

response.write(chunk, [encoding])

write a chunk of string or buffer to response

response.end([data], [encoding])

This method signals to the server that all of the response headers and body has been sent


Listening to event

server.on('event', function(a, b, c) {
  //do things
});
server is an instance of eventEmitter, eventEmitter has two methods on and emit. emit emits an event, on listens to the event

A variation of the example would be: 

var http = require( "http" );

var server = http.createServer();
server.listen( 9000 );
server.on( 'request',  function(req, res ){
	res.writeHead( 200, { "Content-Type": "text/plain" });
	res.write( "Hello World" );
	res.end();
});
console.log( "localhost:9000 running" );












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值