写一个 nodejs npm 应用 - webhere

2016-07-05 09:59:26 +08:00
 smallyard

前言、没图不说话,先上图。

What's webhere?

有没有遇到这样的场景:写程序的时候,需要访问一个文件,这个文件 需要是放到一台 web 服务器上,但是你不是开发的 web 应用。

所以呢,你不得不去找一个 web 服务器,把你的文件上传上去,或者干脆直接创建一个 web 应用程序...

webhere 就是来解决这个问题,在你想要当做 web 根目录的目录下,打开你亲爱的命令行,敲下 webhere ,回车,搞定。

然后就可以通过 web 浏览器访问目录下的文件了。

# 安装
$ npm install webhere -g

# 运行
$ webhere

一、 原理

原理比较简单,一句话来说,就是搭建一个 web 服务器。

1.用 nodejs 的 http 包创建一个 web 服务。

2.对访问路径路由到具体的文件路径。

3.根据文件是否存在写具体的响应码,根据文件的后缀写具体 Content-type 。

4.返回文件的内容,响应结束。

二、 实现

源码发布在github上,可以直接去看。

三、 用例

#create a web server in the current directory with default port 9000
$ webhere
#create a web server with port 5000
$ webhere -p 5000
#create a web server in the /home directory with port 5000
$ webhere -p 5000 -b /home
#don't open browser
$ webhere -s

四、 参数

Usage: webhere [options]
Options:
   -h, --help             output usage information
   -V, --version          output the version number
   -p, --port <n>         port of web (default 9000)
   -b, --basePath <path>  base path of web (default .)
   -s, --silent           silent mode, don't open browser
1154 次点击
所在节点    程序员
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/290322

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX