nodejs常用API(path、buffer、event、fs)

path

  • normalize、join 、resolve
const {normalize} = require('path')
//等同于es5
// const normalize = require('path').normalize()

//path.normalize() 方法会规范化给定的 path,并解析 '..' 和 '.' 片段。
console.log(normalize('/usr//local/bin'))
console.log(normalize('/usr//lo/../bin'))
/*
输出
/usr/local/bin
/usr/bin
 */
const {join} = require('path')
//path.join拼接路径
console.log(join('/usr','loc','haha/'))
console.log(join('/usr///','..//lll','sds////'))
/*
输出结果
/usr/loc/haha/
/lll/sds/
 */
  • basename 、extname 、dirname
const {basename,dirname,extname} = require(
    'path'
)

const filePath = '/usr/local/bin/no.txt'

console.log(dirname(filePath))
console.log(basename(filePath))
console.log(extname(filePath))

/*
输出结果:
/usr/local/bin
no.txt
.txt
 */
  • parse 、format
const {parse,format} = require('path')
const filePath = '/usr/local/node_modules/n/p.json'
const ret = parse(filePath)
console.log(ret)
console.log(format(ret))

/*
输出结果:
{ root: '/',
  dir: '/usr/local/node_modules/n',
  base: 'p.json',
  ext: '.json',
  name: 'p' }
  
/usr/local/node_modules/n/p.json

 */
  • sep 、delimiter 、win32 、posix
const {sep, delimiter, win32, posix} = require('path')
console.log('sep:',sep)
// sep: /
console.log('win.sep:',win32.sep);
// win.sep: \
console.log('PATH:',process.env.PATH)
console.log('delimiter:',delimiter)
// delimiter: :
console.log('win.delimiter:',win32.delimiter)
// win.delimiter: ;

path

  • __dirname、__filename总是返回文件的绝对路径
  • process.cwd()总是返回执行node命令所在的文件夹

相对路径(./)

  • 在require方法中总是相对当前文件所在文件夹
  • 在其他地方和process.cwd()一样,相对于node启动文件夹

buffer

Buffter特点:

  • Buffer用于处理二进制数据流
  • 实例类似整数数组,大小固定
  • C++代码在V8堆外分配物流内存
  • Buffer.alloc()、Buffer.allocUnsafe()、Buffer.from()
console.log(Buffer.alloc(10))
console.log(Buffer.alloc(20))
console.log(Buffer.alloc(5,1))
//不会清空原有的内存
console.log(Buffer.allocUnsafe(5,1))
console.log(Buffer.from([1,2,3]))
console.log(Buffer.from('test'))
console.log(Buffer.from('test','base64'))

console.log(Buffer.from('你好','utf-8'))

/*








 */
  • Buffer.byteLength、Buffer.isBuffer()、Buffer.concat()
/*
Buffer.byteLength
Buffer.isBuffer()
Buffer.concat()
 */

console.log(Buffer.byteLength('test'))//4
console.log(Buffer.byteLength('测试'))//6

console.log(Buffer.isBuffer({}))//false
console.log(Buffer.isBuffer(Buffer.from([1,2,3,4])))//true

const buf1 = Buffer.from('this')
const buf2 = Buffer.from('is')
const buf3 = Buffer.from('a')
const buf4 = Buffer.from('concat')

const buf = Buffer.concat([buf1,buf2,buf3,buf4])

console.log(buf)//
  • buf.length、buf.toString()、buf.fill()、buf.equals()、buf.indexOf()、buf.copy()
/*
buf.length
buf.toString()
buf.fill()
buf.equals()
buf.indexOf()
buf.copy()
 */

var buf = Buffer.from('buf.length')
console.log(buf.length)

buf = Buffer.allocUnsafe(5)
buf[0]=22
console.log(buf.length)

console.log(buf.toString('base64'))
console.log(buf.toString('utf-8'))

const buf3 = Buffer.allocUnsafe(10)

console.log(buf3)
console.log(buf3.fill(10,2,6))

const buf4 = Buffer.from('test')
const buf5 = Buffer.from('test')
const buf6 = Buffer.from('test!')

console.log(buf4.equals(buf5))
console.log(buf4.equals(buf6))

console.log(buf4.indexOf('es'))
console.log(buf4.indexOf('esa'))

/*
10
5
FikQlNU=
)��


true
false
1
-1
 */

处理乱码:string_decoder

const {StringDecoder} = require('string_decoder')
const decoder = new StringDecoder('utf8')
const buf = Buffer.from('中文字符串!理你理你')

for (let i = 0; i < buf.length; i += 5) {
    const b = Buffer.allocUnsafe(5)
    buf.copy(b, 0, i);
    console.log(b.toString())
}

for (let i = 0; i < buf.length; i += 5) {
    const b = Buffer.allocUnsafe(5)
    buf.copy(b, 0, i);
    console.log(decoder.write(b))
}

event

  • EventEmitter
const EventEmitter = require('events')
class myEvent extends EventEmitter{

}
var index = 0;
const ce = new myEvent()

ce.on('test',()=>{
    console.log('this is a eventEmitter')
})

var timer = setInterval(()=>{
    if(index++>20){
        clearInterval(timer)
    }
    ce.emit('test')
},500)
  • once
const EventEmitter = require('events')
class myEvent extends EventEmitter{

}
var index = 0;
const ce = new myEvent()

ce.on('test',()=>{
    console.log('this is a eventEmitter')
})

var timer = setInterval(()=>{
    if(index++>20){
        clearInterval(timer)
    }
    ce.emit('test')
},500)
  • 多个参数
const EventEimtter = require('events')

class CustomEvent extends EventEimtter {
}

const ce = new CustomEvent()
ce.on('error', (err, time) => {
   console.log(err)
   console.log(time)
})

ce.emit('error', new Error('oppsliving'), Date.now())
  • remove
const EventEmitter = require('events')
class CustomEvent extends EventEmitter{}
const ce = new CustomEvent()
function fn1() {
    console.log('fn1')
}
function fn2() {
    console.log('fn2')
}
ce.on('test',fn1)
ce.on('test',fn2)

setInterval(()=>{
    ce.emit('test')
},500)

setTimeout(()=>{
    ce.removeListener('test',fn2)
},2500)

setTimeout(()=>{
    ce.removeAllListeners('test')
},1000)

fs

  • readFile、writeFile、readFileSync、unlink
const fs = require('fs')
fs.readFile('../buffer/decode.js', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data)
})
const content = Buffer.from('this is a test fs buffer')
fs.writeFile('./text.txt', content, {
    encoding: 'utf8'
}, err => {
    if (err) throw err
    console.log('done')
})

const data = fs.readFileSync('../event/once.js', 'utf8')
console.log(data + '\n\n\n')

//删除文件
fs.unlink('./text',err=>{
    if(err)throw err
})
  • stat、rename、readdir
const fs = require('fs')

fs.stat('../event/params.js',(err,stats)=>{
    if(err){
        console.log('文件不存在')
        return
    }
    console.log(stats.isFile())
    console.log(stats.isDirectory())

    console.log(stats)
})

fs.rename('./text.txt','test.md',err=>{
    if(err)throw err
    console.log('done!')
})

fs.readdir('./',(err,files)=>{
    if(err)throw err
    console.log(files)
})

fs.mkdir('test',err=>{
    if(flag<50)return
    fs.rmdir('test',err=>{})
})
  • watch、createReadStream、createWriteStream
const fs = require('fs')

fs.watch('./',{
    //递归
    recursive:true
},(eventType,filename)=>{
    console.log(eventType,filename)
})

//流:有方向的数据
const fs = require('fs')
const rs = fs.createReadStream('./readdir.js')

//process.stdout导出到控制台
rs.pipe(process.stdout)


const ws = fs.createWriteStream('./test.txt')

const tid = setInterval(()=>{
    const num = parseInt(Math.random()*10)
    console.log(num)
    if(num<8){
        ws.write(''+num)
    }else {
        clearInterval(tid)
        ws.end()
    }
},500)

ws.on('finish',()=>{
    console.log('done')
})
  • promisify解决地狱回调问题
const fs = require('fs')
const promisify = require('util').promisify

const read = promisify(fs.readFile)

read('./watch.js').then(data=>{
    console.log(data.toString())
}).catch(ex=>{
    console.log(ex)
})

async function test() {
    try {
        const content = await read('./watch.js')
        console.log(content.toString())
    }catch (ex){
        console.log(ex)
    }
}

test()

es6语法封装promisify,它其实就是一个promise对象

const fs = require('fs')
//模拟promisify
function Promisify(fn) {
    return function (...args) {
        return new Promise((resolve,reject)=>{
            fn(...args,(err,res)=>{
                if(err)return reject(err)
                resolve(res)
            })
        })
    }
}

const read = Promisify(fs.readFile)

read('test.txt').then(data=>{
    console.log(data.toString())
}).catch(err=>{
    console.log(err)
})

async function test() {
    try {
        const data = await read('./test.md')
        console.log(data.toString())
    }catch (ex){
        console.log(ex)
    }
}

test()

你可能感兴趣的:(nodejs常用API(path、buffer、event、fs))