Skip to content

Latest commit

 

History

History
executable file
·
227 lines (156 loc) · 3.12 KB

9. 文件与目录.md

File metadata and controls

executable file
·
227 lines (156 loc) · 3.12 KB

Node.js基础 文件与目录

⭐ by calidion


fs包

  1. 对POSIX的简单封装
  2. 提供了同步或者异步的接口
  3. 异步接口接收最后一个函数为回调函数
  4. 回调函数的第一个参数是错误信息,当返回null或者undefined的值的时候表示成功
  5. 同步版会立即影响错误,并发起异常,可以通过try/catch捕获

同步与异步接口

const fs = require('fs');
const file = '/tmp/hello';

同步:

fs.unlinkSync(file);
console.log('successfully deleted ' + file);

异步:

fs.unlink(file, (err) => {
  if (err) throw err;
  console.log('successfully deleted ' + file);
});

文件的操作

  1. 文件的创建
const fs = require("fs");
const filename = "temp.txt";
fs.createWriteStream(filename);
//或者
fs.openSync(filename, "w+");
  1. 文件的删除
fs.unlinkSync(filename);
fs.unlink(filename, (err) => {
});
  1. 文件读取
const rs = fs.createReadStream(filename);
rs.on("data", (chunk) => {
	console.log(chunk);
	console.log("on reading data" + chunk);
});


  1. 文件或者目录存在
if (fs.existsSync(filename)) {
	  console.log("file exists");
} else {
	  console.log("file not exist");
}

  1. 文件重命名 ===
const filename = "temp.txt";
const newfilename = "temp1.txt";
fs.renameSync(filename, newfilename);

  1. 判断文件类型
fs.statSync(filenanme);

目录操作

  1. 创建目录
const fs = require('fs');
fs.mkdirSync("tmp");
  1. 读取目录
const fs = require('fs');
const dir = fs.readdirSync(".");
console.log(dir);

  1. 创建临时目录
fs.mkdtempSync(path.join(os.tmpdir(), 'foo-'));

path包

用于处理路径与文件名等

  1. 获取文件名
path.basename('/foo/bar/baz/asdf/quux.html');
// Returns: 'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html');
// Returns: 'quux'
  1. 获取文件路径
path.dirname('/foo/bar/baz/asdf/quux');
// Returns: '/foo/bar/baz/asdf'

  1. 获取文件扩展名
path.extname('index.html');
// Returns: '.html'

path.extname('index.coffee.md');
// Returns: '.md'

path.extname('index.');
// Returns: '.'

path.extname('index');
// Returns: ''

path.extname('.index');
// Returns: ''

  1. 路径链接
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'

path.join('foo', {}, 'bar');
// throws 'TypeError: Path must be a string. Received {}'
  1. 分析路径信息
path.parse('/home/user/dir/file.txt');
// Returns:
// { root: '/',
//   dir: '/home/user/dir',
//   base: 'file.txt',
//   ext: '.txt',
//   name: 'file' }

  1. 拼接目录
path.resolve('/foo/bar', './baz');
// Returns: '/foo/bar/baz'

path.resolve('/foo/bar', '/tmp/file/');
// Returns: '/tmp/file'

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// if the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'