全局变量
全局变量是指我们在任何js文件的任何地方都可以使用的变量。
__dirname:当前文件的目录
__filename:当前文件的绝对路径
console:控制台对象,可以输出信息
process:进程对象,可以获取进程的相关信息,环境变量等
setTimeout/clearTimeout:延时执行
setInterval/clearInterval:定时器
fs模块
文件传输
//err参数:错误信息,没有错误将返回null
//data参数:返回文件的内容
var fs = require("fs");
fs.readFile("./aaa/01.txt", function(err, date) {//readFile F一定要大写
if(err){
console.log(err + "打开文件夹错误");
return;
}
//读取的是信息流,是Buffer是缓冲的二进制,用toString()转为字符串
console.log(date.toString());
});
http模块
http 模块主要是用于创建一个能够处理和响应 http 响应的服务
那么我们综合这两个模块写个http请求获取文件的案例:
//导入文件模块
const fs = require("fs");
//导入http模块
const http = require("http");
//创建http服务
const server = http.createServer((request,response) => {
//1.设置响应头 服务器为了告诉浏览器 我返回给你的数据 你用utf-8来解析
//response.setHeader("content-type","text/html;charset=utf-8");
//response.end(request.url);
console.log(request.url);
//请求路径 : ./www/index.html
let reqUrl = request.url;
if (reqUrl === "/index.html") {
fs.readFile("./0722/index.html","utf-8",(err,data) => {
response.end(data);
})
}
})
//开启http服务
server.listen("80",() => {
console.log("start");
})
path模块
path模块提供了一些工具函数,用于处理文件与目录的路径
// 导入模块
const path = require("path");
const fs = require("fs");
const pathName = path.join("name","info","assets","index.html");
console.log(pathName);
// 在使用到路径的地方 使用绝对路径
const txtPath = path.join(__dirname,"novels","01.txt");
console.log(txtPath);
// 读取文件
fs.readFile(txtPath,"utf-8",(err,data) => {
if (!err) {
console.log(data);
} else {
console.log(err);
}
})
nodejs的路径问题
nodejs里面的相对路径是相对于当前运行node命令的终端所处的相对路径,所以为了保证在任何地方打开终端都可以运行。那么我们会想到使用绝对路径。假如文件夹存在其他地方,绝对路径也不可靠。
解决办法:
__dirname 是当前文件所在的文件的绝对路径
__filename 是当前文件的绝对路径
const fs = require("fs");
fs.readFile(__dirname + "\\novels\\01.txt","utf-8",(err,data) => {
console.log(data);
});
console.log(__dirname+"\\novels\\01.txt");
console.log(__filename);