1. 在桌面创建个文件夹,node-server
2. 在这个文件夹里边创建一个js文件,命名为server.js
3. 写代码
var http = require('http');
var Url = require('url');
var FS = require('fs');
var Path = require('path');
const { response } = require('express');
var EXT_MAP = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml"
};
const PORT = 3001;
/** 创建一个web服务器对象 */
const server = http.createServer((request, response)=>{
console.log('>> request.url:', request.url);
//添加响应头
response.setHeader("Access-Control-Allow-Origin", "*");
var pathName = Url.parse(request.url).pathname;
var path = Path.join("./", pathName);
console.log('>> path:', path);
var ext = Path.extname(path);
console.log('>> path1:', path);
ext = ext ? ext.slice(1) : 'unknown';
let exists = FS.existsSync(path);
console.log('>> path3:', exists);
if (!exists) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.write("This request Url " + pathName + " was not found on this server.");
response.end();
} else {
FS.readFile(path, "binary", (err, file) => {
console.log("err::", err);
console.log("file::", file);
if (err) {
response.writeHead(500, {
'Content-Type': 'text/plain'
});
response.end(err.syscall);
} else {
var contentType = EXT_MAP[ext] || "text/plain";
response.writeHead(200, {
'Content-Type': contentType
});
response.write(file, "binary");
response.end();
}
});
}
// FS.exists(path, (exists)=>{
// if (!exists) {
// response.writeHead(404, {
// 'Content-Type': 'text/plain'
// });
// response.write("This request Url " + pathname + " was not found on this server.");
// response.end();
// } else {
// FS.readFile(path, "binary", (err, file) => {
// if (err) {
// response.writeHead(500, {
// 'Content-Type': 'text/plain'
// });
// response.end(err);
// } else {
// var contentType = EXT_MAP[ext] || "text/plain";
// response.writeHead(200, {
// 'Content-Type': contentType
// });
// response.write(file, "binary");
// response.end();
// }
// });
// }
// })
});
//3.监听请求事件
// 4. 启动服务器
server.listen(PORT, () => {
console.log(`Server is running at port ${PORT}...`);
});
4. node server.js; 执行它!
5. 找到mac本地的IPV4地址,加上设置的端口号,就可以访问了。
ipv4地址在这里:mac--设置--网络--Wi-Fi--高级--TCP/IP--IPv4地址;
举个例子 http://192.168.10.103:3001
点开不报错就本地服务起来了。
放张图片上去吧,放到桌面的 我们创建的 node-server 文件夹里。
http://192.168.10.103:3001/xxx.png
好了。完事了!!!
点个赞吧