首先我们需要知道如何运行我们的node项目
随便打开一个js文件,在这个js的终端(cmd)位置输入 node xxx.js(xxx为这个js文件的名字)
废话不多说,直接上代码,一共三个步骤
//一、引用http模块(此模块为系统模块) const http = require('http'); //二、创建一台服务器 var server = http.createServer(function(req,res){ //req 请求 res响应 switch(req.url){ case '/1.html': res.write('111'); //会出输出在浏览器中 break; case '/2.html': res.write('222'); break; default: res.write('404') break; } res.end(); }); //三、 监听 端口(此处我选择的是8080,我们可以选择任意端口) server.listen(8080);
运行node
然后再浏览器中输入 localhost:8080
localhost:8080/1.html
localhost:8080/2.html
FS模块————File System
主要用于文件操作
读文件 fs.readFile(文件名,回调函数)
写文件 fs.writeFile(文件名,内容,回调函数)
写文件 fs.writeFile(文件名,内容,回调函数)
直接上两个最简单的demo
// 引用fs模块 const fs = require('fs'); // 读文件 fs.readFile(文件名,回调函数) fs.readFile('aaa.txt',function(err,data){ if(err){ console.log("读取失败"); }else{ console.log(data) //正常的出来是2进制的 console.log(data.toString()) } }) // 写文件 fs.writeFile(文件名,内容,回调函数) fs.writeFile("bbb.txt","ssssss",function(err){ console.log(err); })
打个广告:淘宝天猫内部优惠群,加我微信拉你进群18801014156