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);
    }
  





猜你喜欢

转载自blog.csdn.net/gexiaopipi/article/details/79583555
今日推荐