File system 文件系统
fs模块的API有三种形态
- Promise
- 回调
- 同步
以下为容易混淆的定义:
描述filehandle.write(buffer[, offset[, length[, position]]])
时,[]
代表可选参数。
FileHandle类
新增于: v10.0.0
FileHandle对象是数字文件描述符的对象封装,只能通过fsPromises.open()方法创建,跟fs.open()
fs.opensync()
返回的fd不是一个东西。
读取文件的几种写法
回调
const { open, read, close } = require('fs');
open('./index.js', function(err, fd) {
if (err) throw err;
read(fd, function(err, bytesRead, buffer) {
console.log(err);
console.log(bytesRead);
console.log(buffer.toString());
});
close(fd, function() {
console.log('操作完毕,关闭文件')
})
});
const { readFile } = require('fs')
readFile('./index.js', 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});
Promise
const { open } = require('fs/promises');
(async function() {
try {
const filehandle = await open('./index.js')
console.log(filehandle)
const result = await filehandle.readFile('utf8')
console.log(result)
filehandle.close()
} catch(err) {
}
})()
const { readFile } = require('fs/promises')
readFile('./index.js', 'utf8').then(res => {
console.log(res)
})
同步
const { readFileSync } = require('fs');
try {
const data = readFileSync('./index.js', 'utf8')
console.log(data)
} catch(err) {
}
const { openSync, readFileSync } = require('fs');
try {
const fd = openSync('./index.js')
const data = readFileSync(fd, 'utf8')
console.log(data)
} catch(err) {
}
path
以下为容易混淆的定义:
'.'
代表当前目录
path.join([...paths])
将所有path片段连接在一起
const path = require('path');
console.log(path.join()); // 返回: '.'
console.log(path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'))
// 返回: '/foo/bar/baz/asdf'
Path.resolve([...paths])
从右到左,将path转化为绝对路径立马停止
最后的/会被删除
const path = require('path');
path.resolve('/foo/bar', '/tmp/file/');
// 返回: '/tmp/file'
如果在处理完所有给定的 path
片段之后,还没有生成绝对路径,则使用当前工作目录。
const path = require('path');
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// 如果当前工作目录是 /home/myself/node,
// 则返回 '/home/myself/node/wwwroot/static_files/gif/image.gif'
如果没有path,返回当前工作目录的绝对路径。
const path = require('path');
path.resolve() // '/Users/ning/work/testspace/file-system'
global全局变量
__filename
console.log(__filename);
// '/Users/ning/work/testspace/file-system/b.js'
__dirname
console.log(__dirname)
// '/Users/ning/work/testspace/file-system'