Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pipe #14

Open
OPY-bbt opened this issue May 5, 2019 · 0 comments
Open

pipe #14

OPY-bbt opened this issue May 5, 2019 · 0 comments
Labels

Comments

@OPY-bbt
Copy link
Owner

OPY-bbt commented May 5, 2019

const fs = require('fs');
const path = require('path');

function pipe(source, target) {
    const rs = fs.createReadStream(source, { highWaterMark: 2 });
    const ws = fs.createWriteStream(target, { highWaterMark: 1 });

    rs.on('data', function(buf) {
        // 如果读取的数据还没有被完全写入文件, 暂停读取
        if (!ws.write(buf)) {
            rs.pause();
        }
    });

    ws.on('drain', function(buf) {
        // 写入已经完成,开启读取。
        console.log('ws drain');
        rs.resume();
    })

    rs.on('end', function(buf) {
        // 调用写入流end方法,完成写入。
        console.log('rs end');
        ws.end();
    })
}

pipe(path.resolve(__dirname, 'a.txt'), path.resolve(__dirname, 'b.txt'));
@OPY-bbt OPY-bbt added the Node.js label May 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant