刚刚入门node,学习了简单的建立服务器并且读取文件,方法是这样滴:
我们先创建一个文件夹(在任何盘符下都可以,名字也随意)
然后呢,在里面再创建一个文件夹,同样名字随意
再然后呢,就写一个.js文件,代码是这样滴
const http = require('http');
const fs = require('fs');
var server = http.createServer(function(req,res){
var file_name = './www'+req.url;
fs.readFile(file_name,function(err,data){
if(err){
res.write('404');
}else{
res.write(data);
}
res.end();
});
});
//端口号
server.listen(8080);
写完之后,在cmd中运行(当然这里需要你在这之前已经调配好了node的环境)
在.js文件所在文件夹打开cmd,或者运行cmd打开.js文件所在文件夹,命令node server.js ,打开浏览器,将地址改为localhost:8080(这里面server.js就是.js文件的名称),这时候会弹出404,如果想要输出文件里面的数据,可以在www文件夹下写新的文件,并对应打开localhost:8080/文件名
例如:我在www文件夹下建了一个index.html,代码是这样
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width:200px;
height:200px;
background:black;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
然后在地址栏输入localhost:8080/index.html,结果就是这样滴