用Node.js创建一个静态服务器
源代码:
var http = require( 'http' );//定义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 === '/'){ //首页html请求为/,要拼接
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 }` )
})
模块/包 与Common.js
Node.js使用了Common.js规范
Node.js中Common.js规范有三种使用类型:
- 内置模块 path url fs precess
- 第三方模块:插件
- 自定义模块
前端模块化
- AMD ( require.js )
- CMD ( sea.js )
- Common.js ( module.export require )
- es6 模块化 ( export import )
终端
- gitbash 客户端软件中的命令 叫 linux命令
- clear 清屏
- ls 列出当前目录下的所有目录和文件
- cmd中的命令叫做 DOS命令
- dir/w 列出当前目录下的所有的目录和文件
- cls 清屏
自定义模块上传 npmjs.com 过程
- 创建package.json
第一个js文件 - var { name } = require(’./name.js’)
var student = {
id: 1,
name: ‘peter勇’
}
// console.log(student.name)
module.exports = {
student,
name
}
第二个js文件
var name = {
txt: ‘强哥无敌’
}
module.exports = { name }
3. 在 http://npmjs.com 上注册账号
4. 激活账号( npmjs.com会发送一个邮件给你的注册邮箱 )
5. 使用命令登录npmjs.com ( 登录前将你的源从淘宝源 切到 npmjs)
- 问题 : 如何切换源呢?
- 解决: 使用 nrm 切换
- nrm 安装 `$ npm i nrm -g`
nrm ls 查看终端相应源
nrm use 相应源 实现对应切换
`$ npm adduser`
6. 如果登录成功, 提示为: Logged in as yanyabing on https://registry.npmjs.org/.
7. 发布包到npmjs
`$ npm publish`
8. 在npmjs官网查看包有没有发送上去
9. 下载包来使用一下
`$ npm i 包名称 -S / -D `
新建一个js文件,var student = require('包名称')
console.log(student)