让NodeJS在你的项目中发光发热

开发 前端
其实NodeJS作为真正意义上的服务端语言,在我们开发的时候可以运用NodeJS强大的模块和众多的npm包来为我们自己服务

近些年来借着NodeJS的春风,前端经历了一波大洗牌式得的发展。使得前端开发在效率,质量上有了质的飞跃。可以说NodeJS已经是前端不可欠缺的技能了。但是是事实上大部分的前端对于本地安装的NodeJS的使用可能仅限于node -v和npm了😂。其实NodeJS作为真正意义上的服务端语言,在我们开发的时候可以运用NodeJS强大的模块和众多的npm包来为我们自己服务。

写在前面

注意:这篇文章基本上不会去将一些非常基础的东西,希望大家自备ES6+语法, NodeJS基础, 简单的Linux操作等知识。还有这篇文章侧重点不会放在技术的实现细节,主要是提供一些思路和方向。更加深层次的使用,还是要各位朋友自己去挖掘。而且这篇文章会有点长🎫

快速创建模块

这个部分我之前在加快Vue项目的开发速度中提到过,不过那个版本写的比较简单(糙),而且基本全都都是通过Node写的。说白了就是用NodeJS去代替我们生成需要复制粘贴的代码。

在大型的项目中,尤其是中后台项目在开发一个新的业务模块的时候可能离不开大量的复制粘贴,像中后台项目中可能很多模块都是标准的CURD模块,包括了列表,新增,详情,编辑这些页面。那么这就意味着有大量的重复代码存在,每次复制粘贴完之后还有修修改改删删等一大堆麻烦事儿,最重要的是复制粘贴很容易忘记哪一部分就忘记改了,导致项目做的很糙而且也会浪费不少时间。那我们的需求就是把人工复制粘贴的那部分交给Node去做,力求时间和质量得到双重的保障。

之前在Vue项目中写过这个模块,那接下来的demo我们以一个Vue项目来做示例,项目地址。

前期准备

  • 文件结构划分:视图文件,路由文件,Controler文件该怎么放一定要划分清楚。这个就像是地基,可以根据自己项目的业务去划分,我们的项目目录是下面这样划分   
  1. vue-base-template  
  2.     │   config                            // webpack配置config/q其他一些config文件  
  3.     │   scripts                           // 帮助脚本文件 ===> 这里存放我们的项目脚本文件  
  4.     │   │   template                      // 模块文件  
  5.     │   │   build-module.js               // build构建脚本  
  6.     │   │     
  7.     └───src                               // 业务逻辑代码  
  8.     │   │   api                           // http api 层  
  9.     │   └── router                        // 路由文件  
  10.     │   │     │  modules                  // 业务路由文件夹  ==> 业务模块路由生成地址  
  11.     │   │           │ module.js           // 制定模块  
  12.     │   │   store                         // vuex  
  13.     │   └── views                         // 视图文件  
  14.     │   │     │  directory                // 抽象模块目录  
  15.     │   │     │      │  module            // 具体模块文件夹  
  16.     │   │     │      │    │ index.vue     // 视图文件  
  17.     │   │   global.js                     // 全局模块处理  
  18.     │   │   main.js                       // 入口文件 

业务模块我基本上是通过抽象模块+具体模块的方式去划分:

  •   抽象模块:在这里指的是没有具体的功能页面只是一系列业务模块的汇总,相当于一个包含各个具体模块的目录。
  •   具体模块:指的是有具体功能页面的模块,包含着各个具体的页面。

这个划分方式很灵活,主要是根据自己的需求来。

  •     定制模板文件:主要是用于生成文件的模板 比如.vue这种文件
  •     技术准备:

    理论上来讲我们需要用到以下一些npm模块, 起码要知道这个都是干什么的

  •   dotenv: 配置文件管理
  •   inquirer: 命令行交互
  •   chalk: 美化命令行输出
  •   创建流程

    流程很简单我画的也不好,凑合看吧。抽空我会重新画的😂

  

开始撸

自从有了这个想法之后, 这个脚本到现在已经是我第三遍撸了。从第一次的单一简单,到现在的功能完善。我最大的感触就是这个东西开发起来好像没有什么尽头,每一次都能找到不一样的需求点,每次都能找到可以优化的部分。针对自己的项目,脚本可以很简单也可以很复杂。很魔性, 对我来说肯定还有第四次第五次的重构。

为了后期的维护,我把所有的脚本相关NodeJS代码放到了根目录下的scripts文件夹中:

  1. scripts                             // 帮助脚本文件 ===> 这里存放我们的项目脚本文件  
  2. └───template                        // template管理文件夹  
  3. │   │   index.js                    // 模块文件处理中心  
  4. │   │   api.template.js             // api模块文件  
  5. │   │   route.template.js           // route模块文件  
  6. │   │   template.vue                // view模块文件  
  7. │   build-module.js                 // 创建脚本入口文件  
  8. │   │     
  9. |   .env.local                      // 本地配置文件  
  10. │   │                                 
  11. │   util.js                         // 工具文件 

下面我们一个部分一个部分的来讲这些文件的作用(<font color="red">大量代码预警</font>)

  •     build-module.js: 入口文件, 与使用者进行交互的脚本。 通过问答的方式得到我们需要的三个核心变量目录(抽象模块), 模块(具体模块), 注释。如果是第一次执行这个脚本, 那么还会有配置相关的问题, 第一次设置完之后接下来的使用将不会再询问,若想修改可自己修改.env.local文件。这里我不详细描述了, 大部分解释都写在注释里面了。

第一部分 配置文件已经输入项处理部分 

  1. const inquirer = require('inquirer')  
  2. const path = require('path')  
  3. const { Log, FileUtil, LOCAL , ROOTPATH} = require('./util')  
  4. const { buildVueFile, buildRouteFile, buildApiFile, RouteHelper } = require('./template')  
  5. const EventEmitter = require('events');  
  6. // file options  
  7. const questions = [  
  8.   {  
  9.     type: 'input',  
  10.     name: 'folder',  
  11.     message: "请输入所属目录名称(英文,如果检测不到已输入目录将会默认新建,跳过此步骤将在Views文件夹下创建新模块):"  
  12.   },  
  13.   {  
  14.     type: 'input',  
  15.     name: 'module',  
  16.     message: "请输入模块名称(英文)",  
  17.     // 格式验证  
  18.     validate: str => ( str !== '' && /^[A-Za-z0-9_-]+$/.test(str))  
  19.   },  
  20.   {  
  21.     type: 'input',  
  22.     name: 'comment',  
  23.     message: "请输入模块描述(注释):"  
  24.   },  
  25.  
  26. // local configs   
  27. const configQuestion = [  
  28.   {  
  29.     type: 'input',  
  30.     name: 'AUTHOR',  
  31.     message: "请输入作者(推荐使用拼音或者英文)",  
  32.     // 格式验证  
  33.     validate: str => ( str !== '' && /^[\u4E00-\u9FA5A-Za-z]+$/.test(str)),  
  34.     when: () => !Boolean(process.env.AUTHOR)  
  35.   },  
  36.   {  
  37.     type: 'input',  
  38.     name: 'Email',  
  39.     message: "请输入联系方式(邮箱/电话/钉钉)"  
  40.   }  
  41.  
  42. // Add config questions if local condfig does not exit  
  43. if (!LOCAL.hasEnvFile()) {  
  44.   questions.unshift(...configQuestion)  
  45.  
  46. // 获取已经完成的答案  
  47. inquirer.prompt(questions).then(answers => {  
  48.   // 1: 日志打印  
  49.   Log.logger(answers.folder == '' ? '即将为您' : `即将为您在${answers.folder}文件夹下` + `创建${answers.module}模块`)  
  50.   // 2: 配置文件的相关设置  
  51.   if (!LOCAL.hasEnvFile()) {  
  52.     LOCAL.buildEnvFile({  
  53.       AUTHOR: answers.AUTHOR,  
  54.       Email: answers.Email  
  55.     })  
  56.   }  
  57.   // 3: 进入文件和目录创建流程  
  58.   const {  
  59.     folder, // 目录  
  60.     module, // 模块  
  61.     comment // 注释  
  62.   } = answers  
  63.   buildDirAndFiles(folder, module, comment)  
  64. })  
  65. // 事件处理中心  
  66. class RouteEmitter extends EventEmitter {}  
  67. // 注册事件处理中心  
  68. const routeEmitter = new RouteEmitter()   
  69. routeEmitter.on('success', value => {  
  70.   // 创建成功后正确退出程序  
  71.   if (value) {  
  72.     process.exit(0)  
  73.   }  
  74. }) 

第二部分 实际操作部分 

  1. // module-method map  
  2. // create module methods  
  3. const generates = new Map([  
  4.   // views部分  
  5.   // 2019年6月12日17:39:29 完成  
  6.   ['view', (folder, module, isNewDir , comment) => {  
  7.     // 目录和文件的生成路径  
  8.     const folderPath = path.join(ROOTPATH.viewsPath,folder,module)  
  9.     const vuePath = path.join(folderPath, '/index.vue')  
  10.     // vue文件生成  
  11.     FileUtil.createDirAndFile(vuePath, buildVueFile(module, comment), folderPath)  
  12.   }],  
  13.   // router is not need new folder  
  14.   ['router', (folder, module, isNewDir, comment) => {  
  15.     /**  
  16.      * @des 路由文件和其他的文件生成都不一样, 如果是新的目录那么生成新的文件。  
  17.      * 但是如果module所在的folder 已经存在了那么就对路由文件进行注入。  
  18.      * @reason 因为我们当前项目的目录分层结构是按照大模块来划分, 即src下一个文件夹对应一个router/modules中的一个文件夹  
  19.      * 这样做使得我们的目录结构和模块划分都更加的清晰。  
  20.      */  
  21.     if (isNewDir) {  
  22.       // 如果folder不存在 那么直接使用module命名 folder不存在的情况是直接在src根目录下创建模块  
  23.       const routerPath = path.join(ROOTPATH.routerPath, `/${folder || module}.js`)  
  24.       FileUtil.createDirAndFile(routerPath, buildRouteFile(folder, module, comment))  
  25.     } else {  
  26.       // 新建路由helper 进行路由注入  
  27.       const route = new RouteHelper(folder, module, routeEmitter)  
  28.       route.injectRoute() 
  29.      }  
  30.   }],  
  31.   ['api', (folder, module, isNewDir, comment) => {  
  32.     // inner module will not add new folder  
  33.     // 如果当前的模块已经存在的话那么就在当前模块的文件夹下生成对应的模块js  
  34.     const targetFile = isNewDir ? `/index.js` : `/${module}.js`  
  35.     // 存在上级目录就使用上级目录  不存在上级目录的话就是使用当前模块的名称进行创建  
  36.     const filePath = path.join(ROOTPATH.apiPath, folder || module)  
  37.     const apiPath = path.join(filePath, targetFile)  
  38.     FileUtil.createDirAndFile(apiPath, buildApiFile(comment), filePath)  
  39.   }]  
  40. ])  
  41. /**  
  42.  * 通过我们询问的答案来创建文件/文件夹  
  43.  * @param {*} folder 目录名称  
  44.  * @param {*} module 模块名称  
  45.  * @param {*} comment 注释  
  46.  */  
  47. function buildDirAndFiles (folder, module, comment) {  
  48.   let _tempFloder = folder || module // 临时文件夹 如果当前的文件是  
  49.   let isNewDir  
  50.   // 如果没有这个目录那么就新建这个目录  
  51.   if (!FileUtil.isPathInDir(_tempFloder, ROOTPATH.viewsPath)) {  
  52.     rootDirPath = path.join(ROOTPATH.viewsPath, _tempFloder)  
  53.     // create dir for path  
  54.     FileUtil.createDir(rootDirPath)  
  55.     Log.success(`已创建${folder ? '目录' : "模块"}${_tempFloder}`)  
  56.     isNewDir = true  
  57.   } else {  
  58.     isNewDir = false  
  59.   }  
  60.   // 循环操作进行  
  61.   let _arrays = [...generates]  
  62.   _arrays.forEach((el, i) => {  
  63.     if (i < _arrays.length) {  
  64.       el[1](folder, module, isNewDir, comment)  
  65.     } else {  
  66.       Log.success("模块创建成功!")  
  67.       process.exit(1)  
  68.     }  
  69.   })  

注: 这里我用了一个generates这个Map去管理了所有的操作,因为上一个版本是这么写我懒得换了,你也可以用一个二维数组或者是对象去管理, 也省的写条件选择了。

  •  template: 管理着生成文件使用的模板文件(vue文件,路由文件, api文件),我们只看其中的route.template.js,其他的部分可以参考项目 
  1. /*  
  2.  * @Author: _author_  
  3.  * @Email: _email_  
  4.  * @Date: _date_  
  5.  * @Description: _comment_  
  6.  */  
  7. export default [  
  8.   {  
  9.     path: "/_mainPath",  
  10.     component: () => import("@/views/frame/Frame"),  
  11.     redirect: "/_filePath",  
  12.     name: "_mainPath",  
  13.     icon: "",  
  14.     noDropdown: false,  
  15.     children: [  
  16.       {  
  17.         path: "/_filePath",  
  18.         component: () => import("@/views/_filePath/index"),  
  19.         name: "_module",  
  20.         meta: {  
  21.           keepAlive: false  
  22.         }  
  23.       }  
  24.     ]  
  25.   }  

在template中最重要的要属index.js了, 这个文件主要是包含了模板文件的读取和重新生成出我们需要的模板字符串, 以及生成我们需要的特定路由代码。template/index.js,文件模板的生成主要是通过读取各个模板文件并转化成字符串,并把的指定的字符串用我们期望的变量去替换, 然后返回新的字符串给生成文件使用。 

  1. const fs = require('fs')  
  2. const path = require('path')  
  3. const os = require('os')  
  4. const readline = require('readline')  
  5. const {Log, DateUtil, StringUtil , LOCAL, ROOTPATH} = require('../util')  
  6. /**  
  7.  * 替换作者/时间/日期等等通用注释  
  8.  * @param {*string} content 内容  
  9.  * @param {*string} comment 注释  
  10.  * @todo 这个方法还有很大的优化空间 
  11.  */  
  12. const _replaceCommonContent = (content, comment) => {  
  13.   if (content === '') return ''  
  14.   // 注释对应列表 comments =  [ [文件中埋下的锚点, 将替换锚点的目标值] ]  
  15.   const comments = [  
  16.     ['_author_', LOCAL.config.AUTHOR],  
  17.     ['_email_', LOCAL.config.Email],  
  18.     ['_comment_', comment],  
  19.     ['_date_', DateUtil.getCurrentDate()]  
  20.   ]  
  21.   comments.forEach(item => {  
  22.     contentcontent = content.replace(item[0], item[1])  
  23.   })  
  24.   return content  
  25.  
  26. /**  
  27.  * 生成Vue template文件  
  28.  * @param {*} moduleName 模块名称  
  29.  * @returns {*string}  
  30.  */  
  31. module.exports.buildVueFile = (moduleName, comment) => {  
  32.   const VueTemplate = fs.readFileSync(path.resolve(__dirname, './template.vue'))  
  33.   const builtTemplate = StringUtil.replaceAll(VueTemplate.toString(), "_module_", moduleName)  
  34.   return _replaceCommonContent(builtTemplate, comment)  
  35.  
  36. /**  
  37.  * @author: etongfu  
  38.  * @description: 生成路由文件  
  39.  * @param {string} folder 文件夹名称   
  40.  * @param {string} moduleName 模块名称  
  41.  * @returns  {*string}  
  42.  */  
  43. module.exports.buildRouteFile = (folder,moduleName, comment) => {  
  44.   const RouteTemplate = fs.readFileSync(path.resolve(__dirname, './route.template.js')).toString()  
  45.   // 因为路由比较特殊。路由模块需要指定的路径。所以在这里重新生成路由文件所需要的参数。  
  46.   const _mainPath = folder || moduleName  
  47.   const _filePath = folder == '' ? `${moduleName}` : `${folder}/${moduleName}`  
  48.   // 进行替换  
  49.   let builtTemplate = StringUtil.replaceAll(RouteTemplate, "_mainPath", _mainPath) // 替换模块主名称  
  50.   builtTemplate = StringUtil.replaceAll(builtTemplate, "_filePath", _filePath) // 替换具体路由路由名称  
  51.   builtTemplate = StringUtil.replaceAll(builtTemplate, "_module", moduleName) // 替换模块中的name  
  52.   return _replaceCommonContent(builtTemplate, comment)  
  53.  
  54. /**  
  55.  * @author: etongfu  
  56.  * @description: 生成API文件  
  57.  * @param {string}  comment 注释  
  58.  * @returns:  {*}  
  59.  */  
  60. module.exports.buildApiFile = comment => {  
  61.   const ApiTemplate = fs.readFileSync(path.resolve(__dirname, './api.template.js')).toString()  
  62.   return _replaceCommonContent(ApiTemplate, comment)  

路由注入, 当输入的目录已存在的时候就不会新建目录文件, 这个时候就会把新模块的路由注入到已存在的目录的路由文件中,效果如下:

这里我们通过RouteHelper来完成对已存在的路由文件进行新模块的路由注入操作,主要通过了stream(流),readline(逐行读取)来实现的。

接下来是干货部分 ==> 首先通过参数找到我们的目标路由文件,然后通过generateRouter()来拼接生成我们需要注入的路由。通过injectRoute方法开始注入路由,在injectRoute中我们首先来生成一个名字为_root临时路径的文件并根据这个路径创建一个writeStream, 然后根据旧的路由文件地址root创建一个readStream并通过readline读写接口去读取原来的路由文件,用一个数组收集旧的路由每一行的数据。读取完毕之后开始遍历temp这个数组并找到第一个children然后把generateRouter()方法返回的数组插入到这个位置。最后使用拼接完成的temp遍历逐行写入writeStream中。最后把原来的root文件删除,把_root重命名为root。一个路由注入的流程就完了。大体的流程就是这样, 关于代码细节不懂得朋友们可以私信我😁。 

  1. /**  
  2.  * @author: etongfu  
  3.  * @description: 路由注入器  
  4.  * @param {string}  dirName  
  5.  * @param {string}  moduleName  
  6.  * @param {event}  event  
  7.  * @returns:  {*}  
  8.  */  
  9. module.exports.RouteHelper = class {  
  10.   constructor (dirName, moduleName, event) {  
  11.     // the dir path for router file  
  12.     this.dirName = dirName  
  13.     // the path for router file  
  14.     this.moduleName = moduleName  
  15.     // 事件中心  
  16.     this.event = event  
  17.     // route absolute path  
  18.     this.modulePath = path.join(ROOTPATH.routerPath, `${dirName}.js`)  
  19.   }  
  20.   /**  
  21.    * Generate a router for module  
  22.    * The vue file path is @/name/name/index  
  23.    * The default full url is http:xxxxx/name/name  
  24.    * @param {*} routeName url default is router name  
  25.    * @param {*string} filePath vue file path default is ${this.dirName}/${this.moduleName}/index  
  26.    * @returns {*Array} A string array for write line  
  27.    */  
  28.   generateRouter (routeName = this.moduleName, filePath = `${this.dirName}/${this.moduleName}/index`) {  
  29.     let temp = [  
  30.       `      // @Author: ${LOCAL.config.AUTHOR}`,  
  31.       `      // @Date: ${DateUtil.getCurrentDate()}`,  
  32.       `      {`,  
  33.       `        path: "/${this.dirName}/${routeName}",`,  
  34.       `        component: () => import("@/views/${filePath}"),`,  
  35.       `        name: "${routeName}"`,  
  36.       `      },`  
  37.     ]  
  38.     return temp  
  39.   }  
  40.   /**  
  41.    * add router to file  
  42.    */  
  43.   injectRoute () {  
  44.     try {  
  45.       const root = this.modulePath  
  46.       const _root = path.join(ROOTPATH.routerPath, `_${this.dirName}.js`)  
  47.       // temp file content  
  48.       let temp = []  
  49.       // file read or write  
  50.       let readStream = fs.createReadStream(root)  
  51.       // temp file  
  52.       let writeStream = fs.createWriteStream(_root)  
  53.       let readInterface = readline.createInterface(  
  54.         {  
  55.           input: readStream  
  56.         // output: writeStream  
  57.         }  
  58.       )  
  59.       // collect old data in file  
  60.       readInterface.on('line', (line) => {  
  61.         temp.push(line)  
  62.       })  
  63.       // After read file and we begin write new router to this file  
  64.       readInterface.on('close', async () => {  
  65.         let _index  
  66.         temp.forEach((line, index) => {  
  67.           if (line.indexOf('children') !== -1) {  
  68.             _index = index + 1  
  69.           }  
  70.         })  
  71.         temptemp = temp.slice(0, _index).concat(this.generateRouter(), temp.slice(_index))  
  72.         // write file  
  73.         temp.forEach((el, index) => {  
  74.           writeStream.write(el + os.EOL)  
  75.         })  
  76.         writeStream.end('\n')  
  77.         // 流文件读写完毕  
  78.         writeStream.on('finish', () => {  
  79.           fs.unlinkSync(root)  
  80.           fs.renameSync(_root, root)  
  81.           Log.success(`路由/${this.dirName}/${this.moduleName}注入成功`)  
  82.           //emit 成功事件  
  83.           this.event.emit('success', true)  
  84.         })  
  85.       })  
  86.     } catch (error) {  
  87.       Log.error('路由注入失败')  
  88.       Log.error(error)  
  89.     }  
  90.   }  

关于路由注入这一块我自己这么设计其实并不是很满意,有更好的方法还请大佬告知一下。

  •   env.local: 配置文件, 这个是第一次使用脚本的时候生成的。没啥特别的,就是记录本地配置项。 
  1. AUTHOR = etongfu  
  2. Email = 13583254085@163.com 
  •  util.js: 各种工具方法,包含了date, file, fs, string, Log, ROOTPATH等等工具方法, 篇幅有限我就贴出来部分代码, 大家可以在项目中查看全部代码:
  1. const chalk = require('chalk')  
  2. const path = require('path')  
  3. const dotenv = require('dotenv')  
  4. const fs = require('fs')  
  5. // 本地配置相关  
  6. module.exports.LOCAL = class  {  
  7.   /**  
  8.    * env path  
  9.    */  
  10.   static get envPath () {  
  11.     return path.resolve(__dirname, './.env.local')  
  12.   }  
  13.   /**  
  14.    * 配置文件  
  15.    */  
  16.   static get config () {  
  17.     // ENV 文件查找优先查找./env.local  
  18.     const ENV = fs.readFileSync(path.resolve(__dirname, './.env.local')) || fs.readFileSync(path.resolve(__dirname, '../.env.development.local'))  
  19.     // 转为config  
  20.     const envConfig = dotenv.parse(ENV)  
  21.     return envConfig  
  22.   }  
  23.   /**  
  24.    * 创建.env配置文件文件  
  25.    * @param {*} config   
  26.    * @description 创建的env文件会保存在scripts文件夹中  
  27.    */  
  28.   static buildEnvFile (config = {AUTHOR: ''}) {  
  29.     if (!fs.existsSync(this.envPath)) {  
  30.       // create a open file  
  31.       fs.openSync(this.envPath, 'w')  
  32.     }  
  33.     let content = ''  
  34.     // 判断配置文件是否合法  
  35.     if (Object.keys(config).length > 0) {  
  36.       // 拼接内容  
  37.       for (const key in config) {  
  38.         let temp = `${key} = ${config[key]}\n`  
  39.         content += temp  
  40.       }  
  41.     }  
  42.     // write content to file  
  43.     fs.writeFileSync(this.envPath, content, 'utf8')  
  44.     Log.success(`local env file ${this.envPath} create success`)  
  45.   }  
  46.   /**  
  47.    * 检测env.loacl文件是否存在  
  48.    */  
  49.   static hasEnvFile () {  
  50.     return fs.existsSync(path.resolve(__dirname, './.env.local')) || fs.existsSync(path.resolve(__dirname, '../.env.development.local'))  
  51.   }  
  52.  
  53. // 日志帮助文件  
  54. class Log {  
  55.   // TODO  
  56.  
  57. module.exports.Log = Log  
  58. // 字符串Util  
  59. module.exports.StringUtil = class {  
  60.     // TODO  
  61.  
  62. // 文件操作Util  
  63. module.exports.FileUtil = class {  
  64.   // TODO  
  65.   /**  
  66.    * If module is Empty then create dir and file  
  67.    * @param {*} filePath .vue/.js 文件路径  
  68.    * @param {*} content 内容  
  69.    * @param {*} dirPath 文件夹目录  
  70.    */  
  71.   static createDirAndFile (filePath, content, dirPath = '') {  
  72.     try {  
  73.       // create dic if file not exit  
  74.       if (dirPath !== '' && ! fs.existsSync(dirPath)) {  
  75.         // mkdir new dolder  
  76.         fs.mkdirSync(dirPath)  
  77.         Log.success(`created ${dirPath}`)  
  78.       }  
  79.       if (!fs.existsSync(filePath)) {  
  80.         // create a open file  
  81.         fs.openSync(filePath, 'w')  
  82.         Log.success(`created ${filePath}`)  
  83.       }  
  84.       // write content to file  
  85.       fs.writeFileSync(filePath, content, 'utf8')  
  86.     } catch (error) {  
  87.       Log.error(error)  
  88.     }  
  89.   }  
  90.  
  91. // 日期操作Util  
  92. module.exports.DateUtil = class {  
  93.   // TODO  

在Util文件中需要注意的部分可能是.env文件的生成和读取这一部分和FileUtil中createDirAndFile, 这个是我们用来生成文件夹和文件的方法,全部使用node文件系统完成。熟悉了API之后不会有难度。

Util文件中有一个ROOTPATH要注意一下指的是我们的路由,views, api的根目录配置, 这个配置的话我建议不要写死, 因为如果你的项目有多入口或者是子项目,这些可能都会变。你也可以选择其他的方式进行配置。 

  1. // root path  
  2. const reslove = (file = '.') => path.resolve(__dirname, '../src', file)  
  3. const ROOTPATH = Object.freeze({  
  4.   srcPath: reslove(),  
  5.   routerPath: reslove('router/modules'),  
  6.   apiPath: reslove('api'),  
  7.   viewsPath: reslove('views')  
  8. })  
  9. module.exports.ROOTPATH = ROOTPATH 
  •  预览

这样的话我们就能愉快的通过命令行快速的创建模块了, 效果如下:

运行

总结

虽然这些事儿复制粘贴也能完成,但是通过机器完成可靠度和可信度都会提升不少。我们的前端团队目前已经全面使用脚本来创建新模块,并且脚本在不断升级中。亲测在一个大项目中这样一个脚本为团队节约的时间是非常可观的, 建议大家有时间也可以写一写这种脚本为团队或者自己节约下宝贵的时间😁

完成机械任务

在开发过程中,有很多工作都是机械且无趣的。不拿这些东西开刀简直对不起他们

SSH发布

注: 如果团队部署了CI/CD,这个部分可以直接忽略。

经过我的观察,很多前端程序员并不懂Linux操作, 有的时候发布测试还需要去找同事帮忙,如果另一个同事Linux功底也不是很好的话,那就可能浪费两个人的很大一块儿时间。今天通过写一个脚本让我们的所有同事都能独立的发布测试。这个文件同样放在项目的scripts文件夹下

前期准备

  •  先配置好Web服务器, 不会的话可以看我之前的一篇文章服务器发布Vue项目指南
  •  需要的技术,都是工具类的包 没什么难度
    •   inquirer: 命令行交互
    •   chalk: 美化命令行输出
    •   ora: 命令行loading
    •   shelljs: 执行shell命令
    •   node-ssh: node SSH
    •   node-ssh: node SSH
    •   zip-local: zip压缩

开始撸

因为是发布到不同的服务器, 因为development/stage/production应该都是不同的服务器,所以我们需要一个配置文件来管理服务器。

deploy.config.js 

  1. module.exports = Object.freeze({  
  2.   // development  
  3.   development: {  
  4.     SERVER_PATH: "xxx.xxx.xxx.xx", // ssh地址  
  5.     SSH_USER: "root", // ssh 用户名  
  6.     SSH_KEY: "xxx", // ssh 密码 / private key文件地址  
  7.     PATH: '/usr/local' // 操作开始文件夹 可以直接指向配置好的地址  
  8.   },  
  9.   // stage  
  10.   stage: {  
  11.     SERVER_PATH: "",  
  12.     SSH_USER: "",  
  13.     SSH_KEY: "",  
  14.     PATH: ''  
  15.   },  
  16.   // production  
  17.   production: {  
  18.     SERVER_PATH: "",  
  19.     SSH_USER: "",  
  20.     SSH_KEY: "",  
  21.     PATH: ''  
  22.   }  
  23. }) 

配置文件配置好了下面开始写脚本, 我们先确定下来流程

  1.  通过inquirer问问题,这是个示例代码, 问题就比较简单了, 在真正使用中包括了发布平台等等不同的发布目标。
  2.  检查配置文件, 因为配置文件准确是必须的
  3.  压缩dist文件,通过zip-local去操作。很简单
  4.  通过node-ssh连接上服务器
  5.  执行删除和备份(备份还没写)服务器上老的文件。
  6.  调用SSH的putFile方法开始把本地文件上传到服务器。 对服务器执行unzip命令。

8: 发布完成🎈

下面是干货代码

第一部分 实际操作部分, 链接SSH, 压缩文件等等 

  1. const fs = require('fs')  
  2. const path = require('path')  
  3. const ora = require('ora')  
  4. const zipper = require('zip-local')  
  5. const shell = require('shelljs')  
  6. const chalk = require('chalk')  
  7. const CONFIG = require('../config/release.confg')  
  8. let config  
  9. const inquirer = require('inquirer')  
  10. const node_ssh = require('node-ssh')  
  11. let SSH = new node_ssh()  
  12. // loggs  
  13. const errorerrorLog = error => console.log(chalk.red(`*********${error}*********`))  
  14. const defaultLog = log => console.log(chalk.blue(`*********${log}*********`))  
  15. const successLog = log => console.log(chalk.green(`*********${log}*********`))  
  16. // 文件夹位置  
  17. const distDir = path.resolve(__dirname, '../dist')  
  18. const distZipPath = path.resolve(__dirname, '../dist.zip')  
  19. // ********* TODO 打包代码 暂时不用 需要和打包接通之后进行测试 *********  
  20. const compileDist = async () => {  
  21.   // 进入本地文件夹  
  22.   shell.cd(path.resolve(__dirname, '../'))  
  23.   shell.exec(`npm run build`)  
  24.   successLog('编译完成')  
  25.  
  26. // ********* 压缩dist 文件夹 *********  
  27. const zipDist =  async () => {  
  28.   try {  
  29.     if(fs.existsSync(distZipPath)) {  
  30.       defaultLog('dist.zip已经存在, 即将删除压缩包')  
  31.       fs.unlinkSync(distZipPath)  
  32.     } else {  
  33.       defaultLog('即将开始压缩zip文件')  
  34.     }  
  35.     await zipper.sync.zip(distDir).compress().save(distZipPath);  
  36.     successLog('文件夹压缩成功')  
  37.   } catch (error) {  
  38.     errorLog(error)  
  39.     errorLog('压缩dist文件夹失败')  
  40.   }  
  41.  
  42. // ********* 连接ssh *********  
  43. const connectSSh = async () => 
  44.   defaultLog(`尝试连接服务: ${config.SERVER_PATH}`)  
  45.   let spinner = ora('正在连接')  
  46.   spinner.start()  
  47.   try {  
  48.     await SSH.connect({  
  49.       host: config.SERVER_PATH,  
  50.       username: config.SSH_USER,  
  51.       password: config.SSH_KEY  
  52.     })  
  53.     spinner.stop()  
  54.     successLog('SSH 连接成功')  
  55.   } catch (error) {  
  56.     errorLog(err)  
  57.     errorLog('SSH 连接失败');  
  58.   }  
  59.  
  60. // ********* 执行清空线上文件夹指令 *********  
  61. const runCommond = async (commond) => {  
  62.   const result = await SSH.exec(commond,[], {cwd: config.PATH})  
  63.   defaultLog(result)  
  64.  
  65. const commonds = [`ls`, `rm -rf *`]  
  66. // ********* 执行清空线上文件夹指令 *********  
  67. const runBeforeCommand = async () => 
  68.   for (let i = 0; i < commonds.length; i++) {  
  69.     await runCommond(commonds[i])  
  70.   }  
  71.  
  72. // ********* 通过ssh 上传文件到服务器 *********  
  73. const uploadZipBySSH = async () => {  
  74.   // 连接ssh  
  75.   await connectSSh()  
  76.   // 执行前置命令行  
  77.   await runBeforeCommand()  
  78.   // 上传文件  
  79.   let spinner = ora('准备上传文件').start()  
  80.   try {  
  81.     await SSH.putFile(distZipPath, config.PATH + '/dist.zip')  
  82.     successLog('完成上传')  
  83.     spinner.text = "完成上传, 开始解压"  
  84.     await runCommond('unzip ./dist.zip')  
  85.   } catch (error) {  
  86.     errorLog(error)  
  87.     errorLog('上传失败')  
  88.   }  
  89.   spinner.stop()  

第二部分 命令行交互和配置校验

  1. // ********* 发布程序 *********  
  2. /**  
  3.  * 通过配置文件检查必要部分  
  4.  * @param {*dev/prod} env   
  5.  * @param {*} config   
  6.  */  
  7. const checkByConfig = (env, config = {}) => {  
  8.   const errors = new Map([  
  9.     ['SERVER_PATH',  () => {  
  10.       // 预留其他校验  
  11.       return config.SERVER_PATH == '' ? false : true  
  12.     }],  
  13.     ['SSH_USER',  () => {  
  14.       // 预留其他校验  
  15.       return config.SSH_USER == '' ? false : true  
  16.     }],  
  17.     ['SSH_KEY',  () => {  
  18.       // 预留其他校验  
  19.       return config.SSH_KEY == '' ? false : true  
  20.     }]  
  21.   ])  
  22.   if (Object.keys(config).length === 0) {  
  23.     errorLog('配置文件为空, 请检查配置文件')  
  24.     process.exit(0)  
  25.   } else {  
  26.     Object.keys(config).forEach((key) => {  
  27.       let result = errors.get(key) ? errors.get(key)() : true  
  28.       if (!result) {  
  29.         errorLog(`配置文件中配置项${key}设置异常,请检查配置文件`)  
  30.         process.exit(0)  
  31.       }  
  32.     })  
  33.   }  
  34.  
  35. // ********* 发布程序 *********  
  36. const runTask = async () => {  
  37.   // await compileDist()  
  38.   await zipDist()  
  39.   await uploadZipBySSH()  
  40.   successLog('发布完成!')  
  41.   SSH.dispose()  
  42.   // exit process  
  43.   process.exit(1)  
  44.  
  45. // ********* 执行交互 *********  
  46. inquirer.prompt([  
  47.   {  
  48.     type: 'list',  
  49.     message: '请选择发布环境',  
  50.     name: 'env',  
  51.     choices: [  
  52.       {  
  53.         name: '测试环境',  
  54.         value: 'development'  
  55.       },  
  56.       {  
  57.         name: 'stage正式环境',  
  58.         value: 'production'  
  59.       },  
  60.       {  
  61.         name: '正式环境',  
  62.         value: 'production'  
  63.       }  
  64.     ]  
  65.   }  
  66. ]).then(answers => {  
  67.   config = CONFIG[answers.env]  
  68.   // 检查配置文件  
  69.   checkByConfig(answers.env, config)  
  70.   runTask()  
  71. }) 

效果预览

至此大家就可以愉快的发布代码了, 无痛发布。亲测一次耗时不会超过30s

打包后钩子

写累了, 改天抽空接着写😀

总结

这些脚本写的时候可能需要一点时间, 但是一旦完成之后就会为团队在效率和质量上有大幅度的提升,让开发人员更见专注与业务和技术。同时时间成本的节约也是不可忽视的,这是我在团队试验之后得出的结论。 以前开发一个模块前期的复制粘贴准备等等可能需要半个小时还要多点, 现在一个模块前期准备加上一个列表页静态开发10分钟搞定。写了发布脚本之后直接就让每一个同事能够独立发布测试环境(正式权限不是每个人都有),并且耗时极短。这些都是实在的体现在日常开发中了。另外Node环境都安装了,不用白不用(白嫖😁😁😁), 各位大佬也可以自己发散思维,能让代码搬的砖就不要自己搬。 

责任编辑:庞桂玉 来源: segmentfault
相关推荐

2011-07-18 09:19:33

Redis

2018-09-27 10:44:35

机器数据splunk

2021-06-02 08:00:57

WebAsyncTas项目异步

2017-08-31 14:23:33

MEC

2017-09-01 09:48:37

MEC 应用

2018-01-20 21:45:08

SDN软件定义网络多层网络

2020-02-27 08:19:05

大数据精准施策复工

2009-06-03 14:57:34

互联网

2021-07-07 05:03:35

Debugger技巧Nodejs

2009-06-24 14:18:47

资源管理敏捷项目

2009-06-24 17:34:58

使用JSF的经验

2009-06-16 13:40:06

OSGiApache Feli

2009-07-21 09:52:06

小型软件项目

2011-06-21 11:05:04

软件项目

2022-03-17 08:34:47

TypeScript项目类型

2022-06-21 14:18:06

RBACTienChin项目

2020-10-27 14:15:42

SpringBoot

2023-10-23 20:26:09

治理Android

2020-11-06 08:13:03

服务器Nodejs客户端

2011-07-22 15:56:18

iPhone Interface Builder
点赞
收藏

51CTO技术栈公众号