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

20.Node.js 使用 fs 模块做文件 copy 的四种方法 #21

Open
ccforward opened this issue Jul 31, 2015 · 0 comments
Open

20.Node.js 使用 fs 模块做文件 copy 的四种方法 #21

ccforward opened this issue Jul 31, 2015 · 0 comments
Assignees
Labels

Comments

@ccforward
Copy link
Owner

首先引入文件模块 var fs = require('fs');

Method 1

function copy(src, target) {
    console.log(target);
    fs.writeFileSync(target, fs.readFileSync(src));
}
  • 代码简短清晰
  • 同步读取文件,容易阻塞
  • 读取大文件时,容易内存溢出
  • 尝试复制一个1.5G的电影 结果内存轻松溢出如图

Method 2

function copy(src, target) {
    var rs = fs.createReadStream(src),
        ws = fs.createWriteStream(target);

    fs.on('data', function(chunk) {
        console.log('read');
        ws.write(chunk, function() {
            console.log('write');
        })
    })

    fs.on('end', function() {
        ws.end();
    })
}
  • 读取大文件时不太容易导致内存溢出
  • 代码比较复杂
  • 由于读取和写入的速度不一样,同样存在内存溢出的风险,不过比 Method 1 好很多

Method 3

根据 Method 2 改进

function copy(src, target) {
    var rs = fs.createReadStream(src),
        ws = fs.createWriteStream(target);

    fs.on('data', function(chunk) {
        console.log('read');
        if (ws.write(chunk, function() {
                console.log('write');
            }) === false) {
            rs.pause();
        } else {
            rs.resume();
        }
    })

    fs.on('end', function() {
        ws.end();
    })
}
  • 同步了读取和写入的速度,没有内存溢出的风险
  • 代码比较复杂

Method 4

node中支持pipe方法,类似于管道,将读出来的内容通过管道写入到目标文件中

function copy(src, target) {
    fs.createReadStream(src).pipe(fs.createWriteStream(target));
}
  • 代码简洁
  • 没有内存溢出的风险

1.64G 的文件用了20秒复制完毕,没有内存溢出

@ccforward ccforward self-assigned this Jul 31, 2015
@ccforward ccforward changed the title 20.nodejs 使用 fs 模块做文件 copy 的四种方法 20.Node.js 使用 fs 模块做文件 copy 的四种方法 Jul 31, 2015
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