结合 Shell 对 Koa 应用运行环境检查

在开发环境中,启动一个koa 应用服务,通常还需要同时启动数据库。比如。Mongodb、mysql 等

如果一直开着数据库服务,在不使用的话,电脑会占一定的性能。然而如果每次手动去启动服务,效率又不高。因此如果我们在执行npm run start启动 koa 应用时,如果可以提前把需要的服务启动起来,那么就会效率高很多。

简单来说就是把我们平时运行的命令写成脚本,在启动时运行即可。

这里以mongodb 为例说明这个过程。

一、mongodb 启动脚本

我们在应用目录下新建脚本文件

/post-process/sh/mongodb.sh

dbPath=$HOME/Documents/database/mongo-db
#start up mongod service
# 这里把mongodb 服务后台运行,错误输出重定向到 ./logs/mongod.log 
mongod --dbpath ${dbPath} > ./logs/mongod.log &

二、利用child-process运行shell 脚本

结合nodejs 的 child_process 模块,写一个运行脚本的方法:


// post-process/index.js
const { exec } = require('child_process');
/**
 * 执行一个 shell 脚本
 * @param {*} shell 
 */
const excecShell = (shell) => {
  exec(`sh ${shell}`, (err, stdout, stderr) => {
    if (err) {
      console.log(err)
      return true
    } else {
      console.log(stdout)
    }
  })
}

/**
 * 检查依赖,其实就是运行一系列脚本
 */
const dependencyCheck = (shellArray) => {
    if (Array.isArray(shellArray)) {
        shellArray.map(item => excecShell(item))
    } else {
        console.log('Illeagal shell queue!')
    }
}
module.exports = {
    excecShell: excecShell,
    dependencyCheck: dependencyCheck
}

三、把检查过程写到config.js 中

还可以把我的执行检查写道config.js 中:


// config/index.js
const fs = require('fs')
const path = require('path')
let scriptPath = path.resolve(path.join('./post-process/sh'))
//console.log(scriptPath)

module.exports = appConfig => {
    // 省略
    ...
    config = {
        preChecksScripts: [
          `${scriptPath}/mongodb.sh`
        ],
    }
   return config
}

四、app.js 中执行检查过程:


const Koa = require('koa')
const app = new Koa()
const appConfig = require('./config')()

// 省略...

// 环境检查脚本
const preCheckTool = require('./post-process')

// 需要检查的脚本数组
const checkScripts = appConfig.preChecksScripts
preCheckTool.dependencyCheck(checkScripts)

// ...

来源:https://segmentfault.com/a/1190000017135577

猜你喜欢

转载自www.cnblogs.com/thatme/p/10162282.html
koa