复制
以 node 复制文件
var fs = require('fs'); var path = require('path'); function copy(obj) { fs.readFile(obj.origin, 'utf-8', function(err, data) { if (err) { console.error(err); } else { fs.writeFile(obj.target, data, 'utf-8', function(err) { if (err) { console.error(err); } else { console.log('\x1B[32m%s\x1B[39m', '复制成功--------' + obj.name); } }); } }); } function resolve(dir) { return path.join(__dirname, '..', dir) } var qurConfig = { name: 'require.config.js', origin: resolve('/src/public/js/request.config.js'), target: resolve('/knowledge/static/js/request.config.js') }; copy(qurConfig);
以上只是一个复制文件的,经过学习,下面做了个复制文件夹的
const EventEmitter = require('events'); const fs = require('fs'); const myEvents = new EventEmitter(); myEvents.on('test', () => { creatDir('../nodelearn/', '../github/', copy); }); myEvents.emit('test'); function copy(f, t) { fs.readdir(f, (err, files) => { if (err) { throw err; return; } files.forEach((file) => { var _f = f + '/' + file; var _t = t + '/' + file; fs.stat(_f, (err, stats) => { if (err) { throw err; return; } if (stats.isFile()) { var readStream = fs.createReadStream(_f); var writeStream = fs.createWriteStream(_t); readStream.pipe(writeStream); } else if (stats.isDirectory()) { creatDir(_f, _t, copy); } }); }); }) } function creatDir(_f, _t, callback) { fs.access(_t, fs.constants.R_OK | fs.constants.W_OK, (err) => { if (err) { fs.mkdir(_t, () => { callback(_f, _t); }); } else { callback(_f, _t); } }) }