npmchenwei111
Version:
test1111
94 lines (70 loc) • 1.95 kB
JavaScript
const watch = require('watch')
const path = require('path')
const fs = require('fs')
const FILE_DIR = '../imgs'
const IMGS_OUT_FILE = 'R_img.js'
let watchMap = {}
function imgFilter (name) {
return new RegExp('(.png|.jpg|.jpeg|.webp|.gif)' + '$').test(name)
}
function getFname (fname) {
let arr = fname ? fname.split('/') : []
return arr[arr.length - 1] || fname || ''
}
function getKey (fname) {
arr = getFname(fname).split('.')
return arr[arr.length - 2] || arr[arr.length - 1]
}
function getValue (fname) {
let fullPath = path.join(FILE_DIR, getFname(fname))
fullPath = fullPath.startsWith('.') ? fullPath : ('./' + fullPath)
return `require('${fullPath}')`
}
function reloadR () {
let newMap = Object.assign(watchMap)
let keys = Object.keys(newMap).sort()
let data = keys.reduce((buffer, key) => {
let value = newMap[key]
if (value) {
buffer = buffer + ' ' + key + ': ' + value + ',\n'
}
return buffer
}, '\n')
console.log('reloadR', data)
fs.writeFile(IMGS_OUT_FILE, `// 脚本自动写入,请勿手动更改
export default {${data}}`, function (err) {
if (err) throw err
console.log('写入成功')
})
}
function watching () {
console.log('watching...')
watch.createMonitor(FILE_DIR, function (monitor) {// Stat object for my zshrc.
monitor.on('created', function (f, stat) {
if (imgFilter(f)) {
console.log(f, 'created')
watchMap[getKey(f)] = getValue(f)
reloadR()
}
})
monitor.on('removed', function (f, stat) {
if (imgFilter(f)) {
console.log(f, 'removed')
watchMap[getKey(f)] = undefined
reloadR()
}
})
})
}
fs.readdir(FILE_DIR, function (err, files) {
console.log('w', err, files)
if (!err) {
files.forEach((fname) => {
if (imgFilter(fname)) {
watchMap[getKey(fname)] = getValue(fname)
}
})
}
reloadR()
watching()
})