Node.js 学习笔记 - 核心模块

使用事件 Events

1.无参数:

  const EventEmitter = require('events');

  class Player extends EventEmitter{}

  var player = new Player();

  player.on('play', () => {
    console.log('正在播放');
  });

  player.emit('play');  

2.有参数:

  const EventEmitter = require('events');

  class Player extends EventEmitter{}

  var player = new Player(;

  player.on('play', (track) => {
    console.log(`正在播放:《${track}》`);
  });

  player.emit('play','告白气球');

3.只执行一次事件:

  const EventEmitter = require('events');

  class Player extends EventEmitter{}

  var player = new Player(;

  player.once('play', (track) => {
    console.log(`正在播放:《${track}》`);
  });

  player.emit('play','告白气球');
  player.emit('play','黑色毛衣');

文件系统 File System

1.获取文件与目录的信息

  const fs = require('fs');

  fs.stat('index.js',(error, stats) => {
    if (error) {
      console.log(error);
    } else {
      console.log(stats);
      console.log(`文件:${stats.isFile()}`);
      console.log(`目录:${stats.isDirectory()}`);
    }
  });

2.创建一个目录

  const fs = require('fs');

  fs.mkdir('logs',(error) => {
    if (error) {
      console.log(error);
    } else {
      console.log('成功创建目录:logs');
    }
  });

3.创建文件并写入内容

  const fs = require('fs');

  fs.writeFile('logs/hello.log', 'hello ~ \n', (error) => {
    if (error) {
      console.log(error);
    } else {
      console.log('Create File Successufully!');
    }
  });

  fs.appendFile('logs/hello.log', 'hello Node.js\n', (error) => {
    if (error) {
      console.log(error);
    } else {
      console.log('Append File Successufully!');
    }
  });

4.读取文件里的内容

  const fs = require('fs');

  fs.readFile('logs/hello.log', 'utf8', (error,data) => {
    if (error) {
      console.log(error);
    } else {
      console.log(data);
    }
  });

5.列出目录里的内容

  const fs = require('fs');

  fs.readdir('logs', (error, files) => {
    if (error) {
      console.log(error);
    } else {
      console.log(files);
    }
  });

6.重命名目录或文件

const fs = require('fs');

fs.rename('logs/hello.log', 'logs/greeting.log', (err) => {
  if (err) throw err;
  console.log('重命名成功');
});

7.删除目录及文件

const fs = require('fs');

fs.readdirSync('logs').map((file) => {
  fs.unlink(`logs/${file}`, (error) => {
    if (error) {
      console.log(error);
    } else {
      console.log(`成功删除了文件:${file}`);
    }
  });
});

fs.rmdir('logs', (error) => {
  if (error) {
    console.log(error);
  } else {
    console.log('成功删除了目录:logs');
  }
});

流 Stream

你可能感兴趣的:(Node.js 学习笔记 - 核心模块)