如何使用fs.readFileSync()获取特定文件

时间:2017-04-12 23:07:29

标签: node.js audio coffeescript atom-editor fs

我正在尝试仅从具有不同文件类型的文件夹中获取音频文件。像图像,视频等..

我做了一个功能来过滤结果,但它只返回我的第一个音频文件,我不知道我做错了什么。

CoffeeScript的:

performSegue(withIdentifier: "Your Identifier Here", sender: self)

有没有办法直接这样做?,无需创建函数或循环。太棒了。这样的事情。

@audioFiles = @getAudioFiles()

getAudioFiles: ->

  allFiles = fs.readdirSync(@pathtoMusic.toString())
  musicFiles = Array
  file = 0
  cont = 0

  #-- I also tried with a for loop --#
  #for file of allFiles
  #  fileName = allFiles[file]

  while(file < allFiles.length)
    fileName = allFiles[file++]
    fileExtension = fileName.split('.').pop();

    if(fileExtension is "mp3") or (fileExtension is "MP3")
      musicFiles[cont++] = fileName
    if(fileExtension is "wav") or (fileExtension is "WAV")
      musicFiles[cont++] = fileName
    if(fileExtension is "3gp") or (fileExtension is "3GP")
      musicFiles[cont++] = fileName
    if(fileExtension is "m4a") or (fileExtension is "M4A")
      musicFiles[cont++] = fileName
    if(fileExtension is "webm") or (fileExtension is "WEBM")
      musicFiles[cont++] = fileName

  return musicFiles

2 个答案:

答案 0 :(得分:1)

如果您打开使用第三方依赖关系,请考虑使用globby

const globby = require('globby');

// Perform a basename-only match if the pattern does not contain
// any slash characters. That is, *.js would be treated as equivalent
// to **/*.js, matching all js files in all directories.
const options = { matchBase: true };
const fileTypes = ['*.mp3', '*.wav', '*.3gp', '*.m4a', '*.webm'];

globby(fileTypes, options).then(paths => {
    console.log(paths);
});

答案 1 :(得分:0)

这样的事情怎么样:

getAudioFiles = =>
  fileExtensions = [
    "mp3"
    "m4a"
    "3gp"
    "wav"
    "webm"
    "etc"
  ]
  allFiles = fs.readDirSync @pathtoMusic.toString()
  musicFiles = (file for file in allFiles when file.replace(/.*\./, '') in fileExtensions)