答案

code/promises/exercise/main.js

/*
  List the content of the folder, filter out the files only
  then copy to the output folder.
*/
const fs = require('fs')
const path = require('path')
const util = require('util')
const readFile = util.promisify(fs.readFile)
const writeFile = util.promisify(fs.writeFile)
const readdir = util.promisify(fs.readdir)
const stat = util.promisify(fs.stat)
const mkdir = util.promisify(fs.mkdir)
const outputFolder = './output'

function isFile(f) {
  return stat(f).then(d => (d.isFile() ? f : ''))
}

function filterFiles(list) {
  return Promise.all(list.map(isFile)).then(files => files.filter(v => v))
}

function readWrite(result) {
  const files = result[1]
  return Promise.all(
    files.map(f => {
      return readFile(f).then(content =>
        writeFile(path.join(outputFolder, f), content)
      )
    })
  )
}

const getFiles = readdir('./').then(filterFiles)
Promise.all([mkdir(outputFolder), getFiles])
  .then(readWrite)
  .then(() => console.log('done!'))
  .catch(e => console.log(e))
用户头像
登录后发表评论