节点 - 浏览JS文件的文件夹并提取某些位

时间:2017-08-18 04:48:00

标签: javascript node.js documentation

我目前正在将测试文档维护为电子表格 - 所以我有3列:

  • 文件名
  • 来自it块的文字 - 它是一个摩卡测试it('does this thing', function(){ ... })
  • 描述 - 我正在写作。

但是我不喜欢这个想法是维护它的时间。

是否可以自动执行此操作,我认为存在一些npm包。因此,这将运行一个文件夹,获取文件名并查看每个JS以在一些已定义的字符串正则表达式之后收集信息。例如,查找//DESCRIPTIONit(之后的任何文字 - 就像这样:

//DESCRIPTION: Some text here
it('does this thing', function(){ ... })

1 个答案:

答案 0 :(得分:2)

使用 esprima 获取 AST ,过滤掉您想要的测试块,通过 escodegen 生成源代码

以下是代码:

const fs = require('fs')
const path = require('path')
const esprima = require('esprima')
const escodegen = require('escodegen')


function walkSync (dir) {
  return fs.statSync(dir).isDirectory()
    ? Array.prototype.concat(...fs.readdirSync(dir).map(f => walkSync(path.join(dir, f))))
    : dir
}

const result = walkSync('./test').map(path => {
  const ast = esprima.parse(fs.readFileSync(path, 'utf8'))
  ast.body = ast.body.filter(elem => {
    return elem.type === 'ExpressionStatement'
      && elem.expression && elem.expression.callee
      && elem.expression.callee.name === 'it'
  })
  const code = escodegen.generate(ast)
  return {
    path,
    code
  }
})

console.log(result)

测试文件夹结构是什么样的: enter image description here

什么测试用例看起来像: enter image description here

执行结果如下: enter image description here

相关问题