node 中的文件读取写入操作

 
//文件复制
var fs = require ('fs');

function copy (src, dst) {
  fs.readFile ('./index4.js', 'utf8', function (err, data) {
    fs.writeFile ('./index5.js', data.toString (), 'utf8', function (
      err,
      data
    ) {
      if (err) {
        console.log ('fail');
      } else {
        console.log ('success');
      }
    });
  });
}

function main (argv) {
  copy (argv[0], argv[1]);
}

main (['./index4.js', './index5.js']);

文件流方式复制;

function Copy (src, dst) {
  fs.createReadStream (src).pipe (fs.createWriteStream (dst));
}

function Main (argv) {
  Copy (argv[0], argv[1]);
}
Main (['./index8.js', './index7.js']);

只读数据流;

function onlyReadStream (src, callback) {
  var rs = fs.createReadStream (src);
  rs.on ('data', function (chunk) {
    rs.pause ();
    callback (chunk);
  });
  rs.on ('end', function () {
    console.log ('end');
  });
}

只写数据流;
function OnlyWriteStream (...arg) {
  var rs = fs.createReadStream (arg[0]);
  var ws = fs.createWriteStream (arg[1]);
  rs.on ('data', function (chunk) {
    if (!ws.write (chunk)) {
      rs.pause ();
    }
  });
  rs.on ('end', function () {
    ws.end ();
  });
  ws.on ('drain', function () {
    rs.resume ();
  });
}

OnlyWriteStream ('./index7.js', './index8.js');

//标准化路径
var path = require ('path');
var obj = {};

function normalize (key, value) {
  obj[path.normalize (key).replace (/\\/g, '/')] = value;
}
normalize ('foo///baz///', 2);
console.log (obj);

//合并路径

var combine = path.join ('foo/', 'baz/', '../bar');
console.log (combine);

//获得文件扩展名

var extname = path.extname ('fwe/fwefw.html');
console.log (extname);

//目录遍历
//fs.statSync(path) 接收一个参数 是fs.stats实例
//异步方法
//fs.stat(path,function(err,stats){})
function travelSync (dir, callback) {
  fs.readdirSync (dir).forEach (function (file) {
    var pathname = path.join (dir, file);
    if (fs.statSync (pathname).isDirectory ()) {
      travelSync (pathname, callback);
    } else {
      callback (pathname);
    }
  





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值