常用的node方法
文章目录
node是什么
node.js是一个异步的事件驱动的JavaScript运行时
node特性
- 非阻塞I/O
- 事件驱动
常用模块
fs
readFile(),异步读取文件
fs.readFile('./config.js',(err,data)=>{
if(err) throw err
console.log(data)
})
readFileSync(),同步读取文件,会产生阻塞效果
const data=fs.readFile('./config.js') //代码会阻塞在这里
console.log
path
path和fs常常搭配使用
resolve()
将路径或路径片段的序列解析为一个绝对路径
const path = require('path')
console.log(path.resolve(_dirname,'./02.js')) //D:\mytest\node\01\02.js
const data =fs.readFile(path.resolve(__dirname,'./03-http.js'),(err,data)=>{
console.log(data.toString())
})
relative(from,to)
返回从from到to的相对路径
const path = require('path')
console.log('01','02.js') //..\mytest\node\01\02.js
目录结构为 D:\mytest\node\01\02.js
util
promisify
将异步方法封装成返回promise实例的方法
const readFile = promisify(fs.readFile)
readFile('./conf.js').then(data=>console.log(data))
promises
const fsp=require('fs').promises
fsp.readFile('./config.js')
.then(data=>console.log(data))
.catch(err=>console.log(err))
http
const http=require('http')
const server=http.createServer((request,reponse)=>{
response.~~~~end('hahahah')
})
server.listen(3000)

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论