path
const path = require('path')//第一种方案可以使用path.join方法配合__dirname常量来实现let mypath = path.join(__dirname,'hello.txt')let mypath2 = path.join(__dirname,'myfiled','hello.txt')//第二个参数相当于上一级目录let mypath3 = path.join(__dirname,'./myfiled/hello.txt')//这样写与第二种一样console.log(mypath);console.log(mypath2);console.log(mypath3);//第二种方案resolve就简单得多,我们只需要给一个相对路径,就能得到一个绝对路径const mypath4 = path.resolve('./myfiled/hello.txt')console.log(mypath4);
fs
fs模块,是Node标准库中用于操作计算机上的文件的模块,提供了很多的方法,比如现在我们想从电脑上读取一个HTML文件,把内容返回给浏览器,就需要用到这个模块
const fs = require('fs');const path = require('path');let filePath= path.join(__dirname,'hello.txt')//同步读取文件const syncContent = fs.readFileSync(filePath,'utf8')console.log(syncContent);//异步读取文件const asyncContent = fs.readFile(filePath,'utf8',(err,data)=>{//err 读取文件错误才不为空if(err){console.log(err);return}//data 读取的数据console.log(data);})console.log(asyncContent);//文件写入fs.writeFile(filePath,'Hellow!!!','utf8',err=>{console.log('写入成功');})
http
使用nodejs写一个服务器
const fs = require('fs')// 1. 引入http协议,node里面已经帮我们封装好了关于这部分的APIconst http = require('http')// 2. 创建一个服务器对象const server = http.createServer()// 3. 绑定ip和端口server.listen(8081,'localhost')// 4. 服务器对象监听浏览器的请求server.on('request',(request,response)=>{//添加请求头,解决中文乱码问题response.setHeader('Content-Type','text/html;charset=utf-8')//返回字符串response.end('<h1>hellow my friend. 你好,我的朋友</h1>')//返回静态资源fs.readFile('./hello.txt',(err,data)=>{response.end(data)})//根据请求url(request.url)统一返回静态资源fs.readFile(__dirname+request.url,(err,data)=>{response.end(data)})//接口if(request.url === '/getArticles'){// 返回一个数组给浏览器 - 但是不能直接返回一个数组,要先把数组转换为字符串,否则会报错let json = JSON.stringify([{id:1,title:'标题1',content:'内容1'},{id:2,title:'标题2',content:'内容2'},{id:3,title:'标题3',content:'内容3'}])response.end(json)}})
