typescript - 如何避免使用 fs-extra.copySync 方法复制 .txt 和 .xml 文件类型
问题描述
我正在做一个打字稿的小任务,目前我正面临下面提到的问题,我无法找到实现这一目标的方法。任何关于下面提到的问题的指导或建议将不胜感激。
我有一个小任务将目录复制到文件系统中的另一个位置,所以目前我在 npm 包中使用 fs-extra.copySync 方法,将目录从一个位置复制到另一个位置,但是当我复制文件时需要排除一些文件类型(.xml、.txt)。
所以问题出在我要复制的目录中,如果有一个子文件夹,那么不允许的文件类型(.xml 和 .txt)也会被复制。所以我尝试了以下方法,但它给出了以下错误。
无法读取 null 的属性“readFiles”
我尝试的方法如下所述。
服务器.ts
function moveFilesAll()
{
var moveFrom = "./src";
var moveTo = "./Destination";
readFiles(moveFrom,moveTo);
}
function readFiles(moveFrom,moveTo)
{
fs.readdir(moveFrom, function (err, files) {
if (err) {
console.error("Could not list the directory.", err);
process.exit(1);
}
files.forEach(function (file, index) {
console.log(file + " "+ index)
// Make one pass and make the file complete
var fromPath = path.join(moveFrom, file);
var toPath = path.join(moveTo, file);
fs.stat(fromPath, function (error, stat) {
if (error) {
console.error("Error stating file.", error);
return;
}
if (stat.isFile())
{
console.log("'%s' is a file.", fromPath);
console.log(path.extname(fromPath));
//files get copying here
if(path.extname(fromPath) =='.txt' || path.extname(fromPath) == '.xml' || path.extname(fromPath) == '.config'){
console.log("Unallowed file types");
}
else
{
console.log("---------------Files copying--------------------------");
fsExtra.copySync(fromPath, toPath);
console.log("copied from '%s' to '%s'. ", fromPath, toPath);
}
}
else if (stat.isDirectory())
{
console.log("=================Directory=============");
console.log("From path "+fromPath);
console.log("TO path "+toPath);
readFiles(fromPath,toPath);
console.log("'%s' is a directory.", fromPath);
}
});
})
})
}
解决方案
您可以使用支持 glob-pattern 的库,例如copy。
npm i --save copy
npm i --save-dev @types/copy
然后像这样使用它。
// Creates the glob pattern for exluded files, result looks like this: '*.xml|*.txt'
const excludedFilesGlob:Array<string> = ['xml', 'txt']
.map(ft => `*.${ft}`)
.join('|');
// The source glob, include all files except for the excluded file types
const source:string = `./src/**/!(${exludedFileTypes})`;
const destination:string = './Destination';
copy(source, destination, (err, files) => {
// This callback is called when either an error occured or all files were copied successfully
if (err) throw err;
// `files` is an array of the files that were copied
});
推荐阅读
- docusignapi - 无法在 SFDC 中接收事件通知
- javascript - 尝试将项目符号添加到 javascript 游戏(到空格键)
- memory - 运行程序的CLion内存使用情况
- python - 将列中的值条件替换为 Pnadas 数据框中的另一列值
- google-apps-script - 谷歌表格多次发布到网络
- javascript - Flask-SocketIO 简单的通信器在 Chrome 和 Firefox 上运行良好,但在 IE 上不行
- python - 如何在python中获取属性的源代码
- html - 即使指向的网站来自我自己的网站,我是否需要将 rel="noopener" 放到每个 target="blank" 中?
- python - 调用matplolib pyplot waitforbuttonpress()时获取键值
- entity-framework - 如何在一个 Razor 页面中访问 2 个 DBContext