zoukankan      html  css  js  c++  java
  • Node.js Command-line(CLI) Applications

    CLI 应用程序

    CLI 应用程序需要在WindowsUnix-like两种系统上运行, 通常是包装两个命令行脚本(cmd脚本和shell脚本, ps1不讨论)添加到系统路径中.

    第一步, 在package.json中设置bin字段

    {
      "name": "FileBrowser",
      "version": "1.0.0",
      "description": "A Online File Browser",
      "bin": {
        "fs": "./index.js"
      },
      "scripts": {
        "start:dev": "nodemon index.js"
      },
      "license": "MIT",
      "dependencies": {
        "express": "^4.17.1"
      }
    }
    

    使用yarn链接

    [sudo] yarn link
    [sudo] yarn unlink
    
    • win
      如果package是CLI程序, 那么会在目录C:UsersAdministratorAppDataLocalYarnin下生成对应的脚本文件.
      并且C:UsersAdministratorAppDataLocalYarnDatalink下会建立目录硬链接(幸运的是Windows可以跨驱动器建立硬链接, 而Linux下的目录只需建立符号链接就可以了, 目录的open操作在系统API层屏蔽了符号链接与硬链接的区别, 需要特意去读取符号链接文件本身属性时有别的open操作API)

    • linux

    root@ubuntu:~/git/FileBrowser# ls -lih /usr/local/bin/fs
    674070 lrwxrwxrwx 1 root root 48 10月 18 02:17 /usr/local/bin/fs -> ../share/.config/yarn/link/file-browser/index.js
    

    显然项目被链接到了/usr/local/share/.config/yarn/link目录, 并且index.js被链接到PATH路径目录/usr/local/bin下.

    使用npm链接或安装

    [sudo] npm link [.]
    [sudo] npm unlink [.]
    

    或者

    [sudo] npm install --global [.]
    [sudo] npm uninstall --global [.]
    
    • win
      win下不是建立可执行文件链接, 而是需要包装一个cmd命令, 使用node执行index.js文件.
    C:UsersAdministratorAppDataRoaming
    pmfs -> C:UsersAdministratorAppDataRoaming
    pm
    ode_modulesfile-browserindex.js
    C:UsersAdministratorAppDataRoaming
    pm
    ode_modulesfile-browser -> E:cygwin64homeAdministratorgitFileBrowser
    
    • linux
      和yarn一样, 命令链接到/usr/local/bin下, 不过项目链接到了/usr/local/lib/node_modules:
    /usr/local/bin/fs -> /usr/local/lib/node_modules/file-browser/index.js
    /usr/local/lib/node_modules/file-browser -> /root/git/FileBrowser
    

    设置process.title以命名cmd窗口

    使用npm运行每个Node.js项目的时候, cmd窗口都会变成"npm"几个字, 非常烦, 就连这种方式启动的cmd窗口也不行:

    start "标题" cmd /c "npm run start:dev"
    

    其实只需要设置process.title就可以了:
    index.js

    #!/usr/bin/env node
    process.title = '文件服务器';
    

    最佳实践

    • bin/[command].js
      bin/[command].js具有固定形式,因此不能是webpack等编译而来,因此,与dist区分开,通过require执行dist脚本:
    #!/usr/bin/env node
    require('../dist/index.js');
    
  • 相关阅读:
    Invalid command 'RewriteEngine'解决办法
    JEZ reCAPTCHA 谷歌验证码插件及使用方法
    一段图片预加载的代码
    Fancybox
    Silverlight4 beta 中的.net ria service自定义用户身份验证之改变
    .net ria service 数据验证(7)
    .net ria services 自定义函数(9)
    C#开发ActiveX控件及制作CAB包
    Silverlight 3.0 中的 Local Connection
    Silverlight3端操作数据库(5)
  • 原文地址:https://www.cnblogs.com/develon/p/13833214.html
Copyright © 2011-2022 走看看