node.js简单应用
源代码:
var http = require( 'http' );
var port = 8080 ;
var hostname = '127.0.0.1'
var path = require( 'path' ) // 磁盘路径处理的模块
var fs = require( 'fs' ) // 操作文件、目录的模块
var url = require( 'url' ) // 处理url
var server = http.createServer( function ( request, response ) {
var staticPath = path.join( __dirname,'static' )
var urlObj = url.parse( request.url )
/* Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/static/css/index.css',
path: '/static/css/index.css',
href: '/static/css/index.css' }
*/
if( urlObj.pathname === '/'){
urlObj.pathname += 'index.html'
}
console.log( urlObj.pathname )
// fs.readFile(路径,字符编码,错误优先的回调函数)
var filePath = path.join( staticPath, urlObj.pathname )
fs.readFile( filePath,'binary',function( error,filecontent ) {
if ( error ){
throw error
}else {
response.write( filecontent, 'binary' )
response.end()
}
})
})
server.listen( port , hostname , function () {
console.log( `The server is runing: http://${ hostname }:${ port }` )
})