基础
- 循环依赖:只执行到引用之前的部分。
- require引入,内部模块,外部模块。用对象名引用引入的模块。
- 直接书写的函数变量等不export是不能使用的,而且一个模块中的函数和变量都会被包裹在一个函数中,不会直接变成全局的。(其中exports是module.exports的一个快捷引用。)
function(exports, require, module, __filename, dirname){}
- global变量,process变量等都是全局变量,可以通过ES6的语法进行赋值取得变量值。
- chrome的调试工具:
node --inspect-brk
,或者vscode的调试工具都可以对node进行调试。 - 全局global
- 几个API
path
//Path
const { resolve, normalize ,join } = require('path');
console.log(resolve('./'));
console.log(join('C:\\','\\Windows'));
console.log(normalize("C:\\Windows/WW"));
const { basename, dirname, extname } = require('path');
const filePath = 'C:\\Windows\\win.ini'
console.log(basename(filePath));
console.log(dirname(filePath));
console.log(extname(filePath));
const {parse, format} = require('path')
console.log(parse(filePath));
console.log(format(parse(filePath)))
const{sep, delimiter, win32, posix} = require('path')
console.log(sep);
console.log(posix.sep);
console.log(delimiter);
console.log(posix.delimiter);
console.log(win32);
console.log(posix);
//console.log('PATH', process.env.PATH);
const path = require('path');
console.log(__dirname);
console.log(__filename);
console.log(path.resolve('./'));
console.log(process.cwd());
buffer
buffer在ES6之前就用到了,处理二进制流。
console.log(Buffer.alloc(10,2));
console.log(Buffer.from('love', 'utf-8'));
const buf = Buffer.allocUnsafe(10);
const len = Buffer.byteLength(buf);
console.log(len);
console.log(Buffer.byteLength(Buffer.from("测试")))
//Buffer.concat()
const {StringDecoder} = require('string_decoder')
const decoder = new StringDecoder('utf-8');
const buf2 = Buffer.from("中文字符串!");
for (let index = 0; index < buf2.length; index += 5) {
const b = Buffer.allocUnsafe(5);
buf2.copy(b, 0, index);
//console.log(b.toString());
console.log(decoder.write(b));
}
//Buffer.concat()
//fill, length, indexOf, equals, copy
event
const EventEmitter = require('events');
class CustomEvent extends EventEmitter{
}
const ce = new CustomEvent();
//ce.once、
ce.on('test', (error, date)=>{
console.log(error + date);
})
setInterval(()=>{
ce.emit('test', new Error("Oops!"), Date.now());
},500);
// setTimeout(()=>{
// ce.removeListener('test', fn2);
// },1500)
fs
异步 -> 回调函数,第一个返回的参数留给异常,Sync都是同步方法。
const fs = require('fs');
const data = fs.readFileSync('./bufferApi.js', 'utf-8');
console.log(data);
fs.writeFile('./test.txt', "This is a wtest", err => {
if(err) throw err;
console.log("Done");
})
//readdir,rename,stats,delete、、、
//watch方法
fs.watch('./',{
recursive: true,
},(event, filename) => {console.log(event + filename);
})
strean
//优雅的流读取,而非读取到内存中
const fs = require('fs');
const rs = fs.createReadStream('./fs.js');
rs.pipe(process.stdout);
//writestream
const ws = fs.createWriteStream('./ws.txt');
const tid = setInterval(()=>{
const num = parseInt(Math.random() * 10);
if(num > 8){
clearInterval(tid);
ws.end();
}else{
ws.write(num.toString());
}
}, 200);
ws.on('finish', ()=>{
console.log('done!');
});
- 回调地狱
大量的()=> {} 会导致回调地狱问题,因此可以用promise和async和await机制:
const fs = require('fs')
const promisify = require('util').promisify;
const read = promisify(fs.readFile);
//promisify方式
read('./ws.txt').then(data => {
console.log(data.toString());
}).catch(ex => {
console.log(ex);
});
//async await方式,这种方式更像是同步的写法
async function asyncRead(){
try {
const content = await read('./ws.txt');
console.log(content.toString());
} catch (error) {
console.log(error);
}
}
asyncRead();