Nice programing

와일드 카드가 일치하는 파일 찾기

nicepro 2020. 12. 11. 19:26
반응형

와일드 카드가 일치하는 파일 찾기


node.js에서 다음과 같은 와일드 카드 일치로 파일을 나열 할 수 있습니까?

fs.readdirSync('C:/tmp/*.csv')?

fs 문서 에서 와일드 카드 일치에 대한 정보를 찾지 못했습니다 .


이것은 Node core에서 다루지 않습니다. 이 모듈 에서 원하는 내용을 확인할 수 있습니다 . npmjs.org는 다양한 모듈을 찾기위한 훌륭한 리소스이기도합니다.

용법

var glob = require("glob")

// options is optional
glob("**/*.js", options, function (er, files) {
  // files is an array of filenames.
  // If the `nonull` option is set, and nothing
  // was found, then files is ["**/*.js"]
  // er is an error object or null.
})

프로젝트에 새 종속성을 추가하지 않으려면 (예 glob:) 다음 과 같은 일반 js / node 함수를 사용할 수 있습니다.

var files = fs.readdirSync('C:/tmp').filter(fn => fn.endsWith('.csv'));

Regex 더 복잡한 비교에 도움이 될 수 있습니다.


glob이 원하는 것이 아니거나 약간 혼란스러운 경우 glob-fs도 있습니다. 설명서는 예제와 함께 많은 사용 시나리오를 다룹니다.

// sync 
var files = glob.readdirSync('*.js', {});

// async 
glob.readdir('*.js', function(err, files) {
  console.log(files);
});

// stream 
glob.readdirStream('*.js', {})
  .on('data', function(file) {
    console.log(file);
  });

// promise 
glob.readdirPromise('*.js')
  .then(function(files) {
    console.log(file);
  });

바퀴를 재발 명 ls하지 마십시오. * nix를 사용하는 경우 도구가 쉽게 수행 할 수 있습니다 ( node api docs )

var options = {
  cwd: process.cwd(),
}
require('child_process')
.exec('ls -1 *.csv', options, function(err, stdout, stderr){
  if(err){ console.log(stderr); throw err };
  // remove any trailing newline, otherwise last element will be "":
  stdout = stdout.replace(/\n$/, '');
  var files = stdout.split('\n');
});

참고 URL : https://stackoverflow.com/questions/21319602/find-file-with-wild-card-matching

반응형