js实现文件合并
使用File API读取文件内容
通过HTML5的File API可以读取用户上传的文件内容。使用FileReader对象异步读取文件内容,将多个文件的内容合并后保存为一个新文件。
function mergeFiles(files, outputFileName) {
const reader = new FileReader();
const mergedContent = [];
let filesProcessed = 0;
files.forEach((file, index) => {
const reader = new FileReader();
reader.onload = function(e) {
mergedContent[index] = e.target.result;
filesProcessed++;
if (filesProcessed === files.length) {
const blob = new Blob(mergedContent, { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
}
};
reader.readAsText(file);
});
}
使用Node.js合并本地文件
在Node.js环境中,可以使用fs模块同步或异步地读取和写入文件,实现文件合并功能。

const fs = require('fs');
const path = require('path');
function mergeFiles(filePaths, outputPath) {
const mergedContent = filePaths.map(filePath => {
return fs.readFileSync(filePath, 'utf8');
}).join('\n');
fs.writeFileSync(outputPath, mergedContent);
}
// 使用示例
mergeFiles(['file1.txt', 'file2.txt'], 'merged.txt');
处理大文件的分块读取
对于大文件,可以采用分块读取的方式避免内存问题。这种方法特别适合Node.js环境处理大型文件。

const fs = require('fs');
const path = require('path');
async function mergeLargeFiles(filePaths, outputPath) {
const writeStream = fs.createWriteStream(outputPath);
for (const filePath of filePaths) {
const readStream = fs.createReadStream(filePath);
await new Promise((resolve, reject) => {
readStream.pipe(writeStream, { end: false });
readStream.on('end', resolve);
readStream.on('error', reject);
});
}
writeStream.end();
}
浏览器端多文件合并下载
在浏览器环境中,可以通过Blob对象将多个文件内容合并后提供下载。
function downloadMergedFile(texts, fileName) {
const blob = new Blob(texts, { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
合并二进制文件
处理二进制文件(如图片、PDF等)时,需要使用ArrayBuffer来正确合并文件内容。
function mergeBinaryFiles(files, outputFileName) {
const readers = files.map(file => {
return new Promise(resolve => {
const reader = new FileReader();
reader.onload = e => resolve(e.target.result);
reader.readAsArrayBuffer(file);
});
});
Promise.all(readers).then(arrayBuffers => {
const totalLength = arrayBuffers.reduce((sum, buffer) => sum + buffer.byteLength, 0);
const mergedArray = new Uint8Array(totalLength);
let offset = 0;
arrayBuffers.forEach(buffer => {
mergedArray.set(new Uint8Array(buffer), offset);
offset += buffer.byteLength;
});
const blob = new Blob([mergedArray], { type: files[0].type });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
});
}






