码迷,mamicode.com
首页 > Web开发 > 详细

nodejs

时间:2018-11-14 14:36:44      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:body   ati   serve   log   htm   creat   ade   binary   pen   

1    第一段代码

var http=require(‘http‘)
var server=http.createServer(function (request,response) {
response.setHeader(‘Content-Type‘,‘text/html‘)
response.write(‘<html><head><meta charset="utf-8"/></head>‘)
response.write(‘<body><h1>你好 node我要学习你了</h1></body>‘)
response.end()

})
console.log(‘open http://localhost:8080‘)
server.listen(8080)

2搭建静态服务器

var http = require(‘http‘)
var fs = require(‘fs‘)
var url = require(‘url‘)
var path = require(‘path‘)
var server = http.createServer(function(request, response){
//获取输入的url解析后的对象
var pathObj = url.parse(request.url, true);
//static文件夹的绝对路径
var staticPath = path.resolve(__dirname, ‘static‘)
//获取资源文件绝对路径
var filePath = path.join(staticPath, pathObj.pathname)
//异步读取file
fs.readFile(filePath, ‘binary‘, function(err, fileContent){
if(err){
console.log(‘404‘)
response.writeHead(404, ‘not found‘)
response.end(‘<h1>404 Not Found</h1>‘)
}else{
console.log(‘ok‘)
response.write(fileContent, ‘binary‘)
response.end()
}
})
})
server.listen(8080)
console.log(‘visit http://localhost:8080‘)

nodejs

标签:body   ati   serve   log   htm   creat   ade   binary   pen   

原文地址:https://www.cnblogs.com/zhangxutao/p/9957185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!