Created
March 3, 2018 09:19
-
-
Save espresso3389/663d496c747deb9a677214e9f6f61092 to your computer and use it in GitHub Desktop.
Aborting file copy on node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
import fs from 'fs-extra'; | |
try { | |
const srcfn = 'sorucefile'; | |
const dstfn = 'tmp.bin'; | |
const src = fs.createReadStream(srcfn); | |
const dst = fs.createWriteStream(dstfn); | |
src | |
.on('end', () => console.log('src:end.')) // EOF到達時 | |
.on('close', () => console.log('src:close.')) // ファイルのclose時 | |
.on('error', e => console.log(`src: ${e}`)); | |
dst | |
.on('close', () => console.log('dst:close.')) | |
.on('error', e => console.log(`src: ${e}`)); | |
// ファイルのコピーを始める; src から dst に push される感じ | |
// 最後まで終われば、次の順序でイベントが発生する。 | |
// つまり、すべてのファイルは自動的に閉じられる | |
// src:end | |
// src:close | |
// dst:close | |
src.pipe(dst); | |
let bytes = 0; | |
src.on('data', chunk => { | |
bytes += chunk.length; | |
// 100MB程度コピーしたところで、コピーをキャンセルしてみる感じ | |
if (bytes > 100 * 1000 * 1000) { | |
console.log('OK, unpipe now.'); | |
src.unpipe(); | |
src.pause(); // これがないと、このコールバックは1回余計に呼び出される | |
src.close(); | |
dst.close(); // これがなくてもファイルは消せる(Windows上でも) | |
fs.unlink(dstfn); // ゴミファイルは消す(なんでcloseしなくても消せるの?) | |
} | |
}); | |
} catch (e) { | |
console.log(e); | |
console.log(e.stack); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment