1.小文件读取
var fs=require('fs');
function copy(src , dst){
//适合小文件读取
fs.writeFileSync(dst,fs.readFileSync(src));
}
function main(args){
copy(args[0],args[1]);
}
//`process`是一个全局变量,可通过`process.argv`获得命令行参数。
//由于`argv[0]`固定等于NodeJS执行程序的绝对路径,
//`argv[1]`固定等于主模块的绝对路径,因此第一个命令行参数从`argv[2]`这个位置开始。
main(process.argv.slice(2));
2.大文件读取
var fs=require('fs');
function copy(src,dst){
//读写大文件
fs.createReadStream(src).pipe(fs.createWriteStream(dst));
}
function main(args){
copy(args[0],args[1]);
}
main(process.argv.slice(2));
3.遍历目录
var fs=require('fs');
var path=require('path');
function travel(dir, callback) {
fs.readdirSync(dir).forEach(function (file) {
var pathname = path.join(dir, file);
if (fs.statSync(pathname).isDirectory()) {
travel(pathname, callback);
} else {
callback(pathname);
}
});
}
//异步遍历
function travel1(dir, callback, finish) {
fs.readdir(dir, function (err, files) {
(function next(i) {
if (i < files.length) {
var pathname = path.join(dir, files[i]);
fs.stat(pathname, function (err, stats) {
if (stats.isDirectory()) {
travel(pathname, callback, function () {
next(i + 1);
});
} else {
callback(pathname, function () {
next(i + 1);
});
}
});
} else {
finish && finish();
}
}(0));
});
}
travel('../../', function (pathnames) {
console.log(pathnames);
});
4.读文件事件的监听
var fs=require("fs");
function copy(src,dst){
var rs = fs.createReadStream(src);//获取stream对象
var ws = fs.createWriteStream(dst);
rs.on('data', function (chunk) {
if (ws.write(chunk) === false) {
rs.pause();
}
});
rs.on('end', function () {
ws.end();
});
//判断什么时候只写数据流已经写入目标了
ws.on('drain', function () {
rs.resume();
});
}
function main(args){
copy(args[0],args[1]);
}
main(process.argv.slice(2));