zoukankan      html  css  js  c++  java
  • 实现node服务器

    一、file_server.js
    'use strict';
    var
        fs = require('fs'),
        url = require('url'),
        path = require('path'),
        http = require('http');
    // 从命令行参数获取root目录,默认是当前目录:
    var root = path.resolve(process.argv[2] || '.');
    console.log('Static root dir: ' + root);
    // 创建服务器:
    var server = http.createServer(function (request, response) {
        // 获得URL的path,类似 '/css/bootstrap.css':
        var pathname = url.parse(request.url).pathname;
        // 获得对应的本地文件路径,类似 '/srv/www/css/bootstrap.css':
        var filepath = path.join(root, pathname);
        // 获取文件状态:
        fs.stat(filepath, function (err, stats) {
            if (!err && stats.isFile()) {
                // 没有出错并且文件存在:
                console.log('200 ' + request.url);
                // 发送200响应:
                response.writeHead(200);
                // 将文件流导向response:
                fs.createReadStream(filepath).pipe(response);
            } else {
                // 出错了或者文件不存在:
                console.log('404 ' + request.url);
                // 发送404响应:
                response.writeHead(404);
                response.end('404 Not Found');
            }
        });
    });
    server.listen(506);
    console.log('Server is running at http://127.0.0.1:506/');
    二、file_bat.bat
    cmd.exe /c start chrome http://127.0.0.1:506/index.html  谷歌浏览器自动打开地址
    node file_server.js
    三、HTML
      index.html
     
    四、本地安装
      npm install -g http-server
      http-server
  • 相关阅读:
    P4387 P4387 【深基15.习9】验证栈序列
    P1241 括号序列题解
    P2058 海港题解
    P1540 机器翻译题解
    leaflet + react + typescript
    TypeScript中文手册:从 JavaScript 迁移到 TypeScript
    react-esri-leaflet与typescript
    TypeError: Super expression must either be null or a function
    前端库(gis前端库和普通库分开)
    react-leaflet:Module parse failed: Unexpected token (10:41)
  • 原文地址:https://www.cnblogs.com/onceweb/p/13685857.html
Copyright © 2011-2022 走看看