-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
在前端这条学习道路上,Node.js 扮演着很重要的角色,在后台/工程化/服务等方面产生出很多工具。
之前并没有系统性的对 Node.js 进行学习,从本文开始,会通过通览API -> 一些知名的npm modules源码分析 -> 进阶使用等方面对 Node.js 进行学习和总结。
首先来看文件系统和路径模块
File System
API
由于是针对 C++ 做的上层封装, Node.js 也无一例外的可以提供对文件/目录的增删读写等接口,同时所有接口都具有同步和异步两种模式。
异步模式接口
const fs = require('fs')
fs.unlink('/tmp/hello', (err) => {
if (err) {
return console.log(err)
}
console.log('successfully deleted /tmp/hello')
})同步模式接口
const fs = require('fs')
try {
fs.unlinkSync('/tmp/hello')
} catch (err) {
console.log(err)
}
console.log('successfully deleted /tmp/hello')常用接口枚举
-
accessSync(path[, mode]) && access(path[, mode], callback) ---- 访问检测
这个接口参数有些特别,mode是一个 File Access Constants 枚举Constant Description F_OK 根据路径可查到 R_OK 可读 W_OK 可写 X_OK 可执行 (Windows下没用,同F_OK) const file = 'package.json'; // Check if the file exists in the current directory, and if it is writable. fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => { if (err) { console.error( `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`); } else { console.log(`${file} exists, and it is writable`); } });
-
appendFile(path, data[, options], callback) && appendFileSync(path, data[, options]) ---- 追加写入