【问题标题】:Search a text between many files in Node.js在 Node.js 中的多个文件之间搜索文本
【发布时间】:2020-03-14 18:20:52
【问题描述】:

使用 jest 和节点,我想检查我的一个文件是否有错误解决的 GIT 冲突。我做了一个可以在我的机器上运行的代码:

const cmd = `find . -not \\( -path ./node_modules -prune \\) -not \\( -path ./.next -prune \\) -not \\( -path ./.git -prune \\) -type f -print0 | xargs -0 grep -li "<<<< HEAD"`

describe('Git conflicts', () => {
  test('All conflicts should be resolved', () => {
    const result = require('child_process')
      .execSync(cmd)
      .toString('utf8')
    expect(result).toBe('./server/__tests__/check-git-conflicts.test.js\n')
  })
})

但是,正如我所说,它可以在我的机器上运行......但它在不同的环境中不起作用,因为我正在直接执行 UNIX 命令。

为了让它更健壮。我想更改该命令:

find . -not \\( -path ./node_modules -prune \\) -not \\( -path ./.next -prune \\) -not \\( -path ./.git -prune \\) -type f -print0 | xargs -0 grep -li "<<<< HEAD

仅用node.js 代码编写它,以便与环境更加兼容。我尝试使用fs.readFile,但尝试失败...

有人知道在 Node.js 中搜索多个文件中的文本的有效方法吗?

【问题讨论】:

    标签: javascript node.js unix testing jestjs


    【解决方案1】:

    我是这样解决的:

    const fs = require('fs')
    
    const toIgnore = [
      'node_modules',
      '.next',
      '.git',
      'check-git-conflicts.test.js',
    ]
    
    function getFilesWithSomeConflict(dir, files_) {
      files_ = files_ || []
    
      fs.readdirSync(dir).forEach(file => {
        const name = dir + '/' + file
        if (toIgnore.includes(file)) return
        if (fs.statSync(name).isDirectory()) {
          getFilesWithSomeConflict(name, files_)
          return
        }
        if (fs.readFileSync(name).includes('<<<< HEAD')) {
          files_.push(name)
        }
      })
    
      return files_
    }
    
    describe('Git conflicts', () => {
      test('All conflicts should be resolved', () => {
        const result = getFilesWithSomeConflict('.')
        expect(result).toHaveLength(0)
      })
    })
    

    【讨论】:

      【解决方案2】:

      使用“process.platform”并将操作系统信息存储在变量中。根据运行的操作系统设置命令。 例如:

      var os = process.platform
      const cmd = ""
      if(os==="linux")
      const cmd = `find . -not \\( -path ./node_modules -prune \\) -not \\( -path ./.next -prune \\) -not \\( -path ./.git -prune \\) -type f -print0 | xargs -0 grep -li "<<<< HEAD"
      

      【讨论】:

      • 不,这正是我不想要的...例如取决于Linux它是否可以工作取决于是否安装了xargs,grep...我正在寻找解决方案Node.js 不执行任何命令。
      猜你喜欢
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 2013-09-04
      相关资源
      最近更新 更多