用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 }` )
})
模块/包 与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
-
在 http://npmjs.com 上注册账号
-
激活账号( npmjs.com会发送一个邮件给你的注册邮箱 )
-
使用命令登录npmjs.com ( 登录前将你的源从淘宝源 切到 npmjs)
- 问题 : 如何切换源呢?
- 解决: 使用 nrm 切换
- nrm 安装
$ npm i nrm -g
$ npm adduser
-
如果登录成功, 提示为: Logged in as yanyabing on https://registry.npmjs.org/.
-
发布包到npmjs
$ npm publish
-
在npmjs官网查看包有没有发送上去
-
下载包来使用一下
$ npm i 包名称 -S / -D