node内置模块

发布时间 2023-12-06 23:06:00作者: adong搬砖
//1.path模块
console.log(path.join('a', 'b', 'c'))//相对路径  a\b\c
console.log(path.resolve('a', 'b', 'c'))//绝对路径  D:\桌面\express\a\b\c
console.log(path.parse('http://web.chenfeng.online'))
// //解析网址
//{root: '', dir: 'http:/', base: 'web.chenfeng.online', ext: '.online', name: 'web.chenfeng'}

//2.url模块
console.log(url.parse("http://web.chenfeng.online"))
// {
//   protocol: 'http:',
//   slashes: true,
//   auth: null,
//   host: 'web.chenfeng.online',
//   port: null,
//   hostname: 'web.chenfeng.online',
//   hash: null,
//   search: null,
//   query: null,
//   pathname: '/',
//   path: '/',
//   href: 'http://web.chenfeng.online/'
// }

//3.fs模块

//同步重写文件内容,参一:文件路径,参二:写入文件内容
fs.writeFileSync(path.join(__dirname, 'public', 'txd.txt'), '同步写入的内容')
//同步读取文件内容,参一:文件路径,参二:编码格式
console.log(fs.readFileSync('txd.txt', 'utf-8'))
//异步重写文件内容,参一:文件路径,参二:写入文件内容,参三:回调函数
fs.writeFile(path.join(__dirname, 'public', 'txd.txt'), '1115', (err, data) => {
  if (err) throw new Error('写入文件异常')
  console.log(err)
  console.log(data)
})
//异步读取文件内容,参一:文件路径,参二:编码格式,参三:回调函数
fs.readFile('txd.txt', 'utf-8', (err, data) => {
  if(err) throw new Error('读取文件异常')
  console.log(data)//读取到的内容
})
//异步追加内容,参一:'文件路径',参二:追加的内容,参三:回调函数
fs.appendFile('txd.txt', '这是追加的内容', (err, data) => {
  if (err) throw new Error('读取文件异常')
  console.log(err)
  console.log(data)
})

//4.http模块
const server=http.createServer((req,res)=>{
  console.log('前端进来了')
  res.end('我给你的数据')
})
server.listen(3000,()=>{
  console.log('http服务启动成功','http://localhost:3000')
})