C:/my/example/directory
:
|- content1.txt
|- content2.txt
|- content3.txt
|- content4.txt
|- content5.txt
然后提供src filenames
-> trg filenames
的映射:
var mapping = {
'content1.txt': 'content7.txt',
'content2.txt': 'content3.txt',
'content3.txt': 'content4.txt',
'content4.txt': 'content2.txt',
'content5.txt': 'content5.txt'
};
所有src filenames
肯定存在。所有trg filenames
肯定是唯一的,但有些trg filenames
可能会映射到某些src filenames
。甚至可能有文件名的周期,它们都需要映射到其他现有文件名,例如content2.txt
-> content3.txt
-> content4.txt
-> content2.txt
。
现在的目标是将映射中每个项目的所有内容从src filename
移到trg filename
。
我最初的解决方案是将所有内容复制到内存中,然后删除所有文件,然后创建所有文件:
const _ = require('underscore'); // Any utility library would do
const fs = require('fs');
const path = require('path');
let readFile = async (filepath) => { /* asynchronously returns a file's content */ };
let writeFile = async (filepath, content) => { /* asynchronously writes a file */ };
let deleteFile = async (filepath) => { /* asynchronously deletes a file */ };
let remapFiles = async (dir, mapping) => {
let fileContents = {};
// After this await all file contents are loaded into `fileContents`
await Promise.all(_.toArray(
_.mapObject(mapping, async (trg, src) => {
fileContents[src] = await readFile(path.join(dir, src));
})
));
// After this await all files are cleaned up
await Promise.all(_.toArray(
_.mapObject(mapping, async (trg, src) => {
await deleteFile(path.join(dir, src))
})
));
// After this await all files are written to their new locations
await Promise.all(_.toArray(
_.mapObject(mapping, async (trg, src) => {
await writeFile(path.join(dir, trg), fileContents[src]);
})
));
};
// Now I can call my function to do the remapping!
remapFiles(path.join('C:', 'my', 'example', 'directory'), mapping)
.then(() => console.log('Remapped!'));
对于这种解决方案,我并不是最幸福的,因为在某些情况下效率很低:
我不想使用任何阻止文件系统的功能。
如何提高remapFiles
的效率?