Skip to content

Instantly share code, notes, and snippets.

@yangjunjun
Last active August 29, 2015 14:01
Show Gist options
  • Save yangjunjun/39069860690aff4fb569 to your computer and use it in GitHub Desktop.
Save yangjunjun/39069860690aff4fb569 to your computer and use it in GitHub Desktop.
nodejs 的 FileSystem相关代码
// 同步读写
fs.writeFileSync('b.txt', fs.readFileSync('a.txt'));
// 异步读写
// 版本一
fs.createReadStream('a.txt').pipe(fs.createWriteStream('b.txt'));
// 版本二
var rs = fs.createReadStream('a.txt');
var ws = fs.createWriteStream('b.txt');
rs.on('data', function (chunk) {
ws.write(chunk);
});
rs.on('end', function () {
ws.end();
});
// 版本三
var rs = fs.createReadStream('a.txt');
var ws = fs.createWriteStream('b.txt');
rs.on('data', function (chunk) {
// 当读取的数据没有写进文件,而是在缓冲区,则停止读取数据流
if (ws.write(chunk) === false) {
rs.pause();
}
});
rs.on('end', function () {
ws.end();
})
// 当读取的数据已经写入文件,则恢复读取数据流
ws.on('drain', function () {
rs.resume();
});
// 参考:http://nqdeng.github.io/7-days-nodejs/#3.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment