V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
smallyard
V2EX  ›  程序员

写一个 nodejs npm 应用 - webhere

  •  1
     
  •   smallyard · 2016-07-05 09:59:26 +08:00 · 1153 次点击
    这是一个创建于 2922 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    webhere

    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
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2422 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:50 · PVG 20:50 · LAX 05:50 · JFK 08:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.