node 基础API(fs)

读文件:

const fs=require(‘fs‘);

fs.readFile(‘./32_readfile.js‘,‘utf8‘,(err,data)=>{
    if(err) throw err;
    console.log(data);
});

const data=fs.readFileSync(‘./32_readfile.js‘,‘utf8‘);  // 同步
console.log(data);

// 输出文件内容

写文件:

const fs=require(‘fs‘);

const content=Buffer.from(‘this is a test‘);

fs.writeFile(‘./text‘,content,err=>{
    if(err) throw err
    console.log(‘done!‘);
})

fs.writeFile(‘./text2‘,‘this is a test2‘,{encoding:‘utf8‘},err=>{
    if(err) throw err
    console.log(‘done!‘);
})

获取文件信息 stat:

const fs=require(‘fs‘);

fs.stat(‘./34_stat.js‘,(err,stats)=>{
    if(err) {
        console.log(‘文件不存在‘)
    };

    console.log(stats.isFile());
    console.log(stats.isDirectory());

    console.log(stats);
});

true
false
Stats {
  dev: 637858,
  mode: 33206,
  nlink: 1,
  uid: 0,
  gid: 0,
  rdev: 0,
  blksize: undefined,
  ino: 23925373020527024,
  size: 200,
  blocks: undefined,
  atimeMs: 1561992748290,
  mtimeMs: 1561992948768.0908,
  ctimeMs: 1561992948768.0908,
  birthtimeMs: 1561992748290.0913,
  atime: 2019-07-01T14:52:28.290Z,
  mtime: 2019-07-01T14:55:48.768Z,
  ctime: 2019-07-01T14:55:48.768Z,
  birthtime: 2019-07-01T14:52:28.290Z }

重命名:

const fs=require(‘fs‘);

fs.rename(‘./text‘,‘test.txt‘,err=>{
    if(err) console.log(‘文件不存在‘);
})

删除:

const fs=require(‘fs‘);

fs.unlink(‘./test.txt‘,err=>{
    if(err) throw err;
    console.log(‘done‘);
})

读文件夹:

const fs=require(‘fs‘);

fs.readdir(‘./‘,(err,data)=>{
    if(err) throw err;
    console.log(data);
})

创建文件夹:

const fs=require(‘fs‘);

fs.mkdir(‘text‘,err=>{
    if(err) throw err;
    console.log(‘done‘);
})

删除文件夹:

const fs=require(‘fs‘);

fs.rmdir(‘text‘,err=>{
    if(err) throw err;
    console.log(‘done‘);
})

监视:

const fs=require(‘fs‘);

fs.watch(‘./‘,{
    recursive:true    // 是否递归(子文件夹)
},(eventType,filename)=>{        // eventType:变化类型
    console.log(eventType,filename);
})

 

node 基础API(fs)

上一篇:LeetCode 957. N 天后的牢房(查找循环节)


下一篇:android表格效果--ListView隔行变色