Skip to content

Instantly share code, notes, and snippets.

@vsashyn
Last active January 2, 2018 13:07
Show Gist options
  • Save vsashyn/4eb0c47a84344838d26f9757c92e2f6a to your computer and use it in GitHub Desktop.
Save vsashyn/4eb0c47a84344838d26f9757c92e2f6a to your computer and use it in GitHub Desktop.
const fs = require('fs')
const path = require('path')
const os = require('os')
const walk = function (dir, done) {
let results = []
fs.readdir(dir, function (err, list) {
if (err) return done(err)
let pending = list.length
if (!pending) return done(null, results)
list.forEach(function (file) {
file = path.resolve(dir, file)
fs.stat(file, function (err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function (err, res) {
results = results.concat(res)
if (!--pending) done(null, results)
})
} else {
results.push(file)
if (!--pending) done(null, results)
}
})
})
})
}
walk('./src', function (err, results) {
if (err) throw err
console.log(results)
// add flow
results.forEach((file) => {
let data = fs.readFileSync(file) ///read existing contents into data
let fd = fs.openSync(file, 'w+')
let buffer = new Buffer('// @flow \r\n')
const flowReg = /@flow/
if (data.toString().split(os.EOL)[0] && !flowReg.test(data.toString().split(os.EOL)[0])) {
fs.writeSync(fd, buffer, 0, buffer.length, 0) //write new data
fs.writeSync(fd, data, 0, data.length, buffer.length) //append old data
fs.close(fd)
} else {
fs.writeSync(fd, data, 0, data.length, 0) //append old data
fs.close(fd)
}
})
console.log('Finish')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment