programing

노드 js를 사용하여 html 파일을 실행하는 방법

topblog 2023. 2. 27. 23:19
반응형

노드 js를 사용하여 html 파일을 실행하는 방법

다음과 같이 angular js를 가진 간단한 html 페이지가 있습니다.

    //Application name
    var app = angular.module("myTmoApppdl", []);

    app.controller("myCtrl", function ($scope) {
        //Sample login function
        $scope.signin = function () {
            var formData =
                    {
                        email: $scope.email,
                        password: $scope.password
                    };
        console.log("Form data is:" + JSON.stringify(formData));
    };
});

HTML 파일:

<html>
    <head>
        <link href="bootstrap.min.css" rel="stylesheet" type="text/css"/>
    </head>

    <body ng-app="myTmoApppdl" ng-controller="myCtrl">
        <div class="container">
            <div class="form-group">
                <form class="form" role="form" method="post" ng-submit="signin()">
                    <div class="form-group col-md-6">
                        <label class="">Email address</label>
                        <input type="email" class="form-control" ng-model="email" id="exampleInputEmail2" placeholder="Email address" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label class="">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword2" ng-model="password" placeholder="Password" required>
                    </div>
                </form>
                <button type="submit" class="btn btn-primary btn-block">Sign in</button>
            </div>
        </div>
    </body>

    <script src="angular.min.js" type="text/javascript"></script>

    <!--User defined JS files-->
    <script src="app.js" type="text/javascript"></script>
    <script src="jsonParsingService.js" type="text/javascript"></script>
</html>

노드 js는 처음입니다.시스템에 노드 js 서버를 설치했는데 노드 js를 사용하여 간단한 html 파일을 실행하는 방법을 잘 모르겠습니다.

내장된 nodejs 웹 서버를 사용할 수 있습니다.

파일 추가server.js예를 들어 다음 코드를 입력합니다.

var http = require('http');
var fs = require('fs');

const PORT=8080; 

fs.readFile('./index.html', function (err, html) {

    if (err) throw err;    

    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(PORT);
});

명령어를 사용하여 콘솔에서 서버를 부팅한 후node server.jsindex.html 페이지는 URL에서 이용할 수 있습니다.http://localhost:8080

http-server를 글로벌하게 설치하기만 하면 됩니다.

npm install -g http-server

html 파일을 실행해야 할 경우 명령어 http-server를 실행합니다.ex의 경우 html 파일은 /home/project/index.html에 있습니다./home/project/$ http-server

그러면 웹 페이지에 액세스할 수 있는 링크가 제공됩니다.http-server Starting up http-server, serving ./ Available on: http://127.0.0.1:8080 http://192.168.0.106:8080

저도 index.html을 엔트리로 하여 nodejs에서 웹 앱을 실행해야 하는 상황에 직면했습니다.제가 한 일은 다음과 같습니다.

  • 달려.node initroot of app (패키지가 생성됩니다)json 파일)
  • 앱의 루트에 express를 설치합니다.npm install --save express(저장하면 패키지가 갱신됩니다.json(고속 의존 관계)
  • 앱의 루트에 공용 폴더를 만들고 진입점 파일(index.filename)과 모든 종속 파일을 저장합니다(이것은 단순화를 위한 것일 뿐, 대규모 애플리케이션에서는 좋은 접근 방식이 아닐 수 있습니다).
  • 앱의 루트에 server.js 파일을 만듭니다.여기에서는 현재 디렉토리에서 공용 폴더에 서비스를 제공하는 노드의 익스프레스 모듈을 사용합니다.
  • server.displaces

    var express = require('express');
    var app = express();
    app.use(express.static(__dirname + '/public')); //__dir and not _dir
    var port = 8000; // you can use any port
    app.listen(port);
    console.log('server on' + port);
    
  • 하다node server: "server on 8000"을 출력합니다.

  • start http://localhost:8000/ : index.display가 호출됩니다.

파일 구조도 비슷합니다.

HTML 파일을 폴더 "www"로 이동합니다.코드 "server.js" 파일을 만듭니다.

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/www'));

app.listen('3000');
console.log('working on 3000');

파일 생성 후 "node server.js" 명령을 실행합니다.

지금까지 가장 간단한 명령어:

npx http-server

이를 위해서는 이 명령어가 실행되는 dir에 기존 index.html이 필요합니다.

Vijaya Simha에 의해 이미 언급되었지만, 저는 npx를 사용하는 것이 훨씬 깨끗하고 짧다고 생각했습니다.몇 달 전부터 이 방법으로 웹 서버를 운영하고 있습니다.

문서: https://www.npmjs.com/package/http-server

http에 액세스하여 8080에서 제공되는html 파일을 가져옵니다.

>npm install -g http-server

>http-server

공용(./public/index.folder) 폴더가 있는 경우, 없는 경우 서버의 루트가 됩니다.폴더를 파라멘터 ex로 보낼 수 있습니다.

http-server [path] [options]

예상 결과:

*> http-server 부팅 중./public 사용 가능일:

http://LOCALIP:8080

http://802.0.0.1:8080

Ctrl+C 키를 눌러 서버를 정지합니다.

http-server가 정지되었습니다.*

이제 http://localhost:8080을 실행할 수 있습니다.

./public 폴더의 index.display가 열립니다.

참고 자료: https://www.npmjs.com/package/http-server

이것은 node.js 파일과 같은 폴더에 저장된 단순한 html 파일 "demo.htm"입니다.

<!DOCTYPE html>
<html>
  <body>
    <h1>Heading</h1>
    <p>Paragraph.</p>
  </body>
</html>

다음은 이 html 파일을 호출하는 node.js 파일입니다.

var http = require('http');
var fs = require('fs');

var server = http.createServer(function(req, resp){
  // Print the name of the file for which request is made.
  console.log("Request for demo file received.");
  fs.readFile("Documents/nodejs/demo.html",function(error, data){
    if (error) {
      resp.writeHead(404);
      resp.write('Contents you are looking for-not found');
      resp.end();
    }  else {
      resp.writeHead(200, {
        'Content-Type': 'text/html'
      });
      resp.write(data.toString());
      resp.end();
    }
  });
});

server.listen(8081, '127.0.0.1');

console.log('Server running at http://127.0.0.1:8081/');

명령 프롬프트에서 위의 nodejs 파일을 초기화하면 "Server running at http://127.0.1:8081/" 메시지가 나타납니다.브라우저에 "http://127.0.0.1:8081/demo.html" 이라고 입력합니다.

프레임워크를 사용하거나 nodejs를 사용하여 자신의 서버를 작성합니다.

단순한 파일 서버는 다음과 같습니다.

import * as http from 'http';
import * as url from 'url';
import * as fs from 'fs';
import * as path from 'path';

var mimeTypes = {
     "html": "text/html",
     "jpeg": "image/jpeg",
     "jpg": "image/jpeg",
     "png": "image/png",
     "js": "text/javascript",
     "css": "text/css"};

http.createServer((request, response)=>{
    var pathname = url.parse(request.url).pathname;
    var filename : string;
    if(pathname === "/"){
        filename = "index.html";
    }
    else
        filename = path.join(process.cwd(), pathname);

    try{
        fs.accessSync(filename, fs.F_OK);
        var fileStream = fs.createReadStream(filename);
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        response.writeHead(200, {'Content-Type':mimeType});
        fileStream.pipe(response);
    }
    catch(e) {
            console.log('File not exists: ' + filename);
            response.writeHead(404, {'Content-Type': 'text/plain'});
            response.write('404 Not Found\n');
            response.end();
            return;
    }
    return;
    }
}).listen(5000);

예를 들어 노드 JS 프로젝트를 통해 html 페이지를 전개하기 위해서는 모든 요구를 index.html로 리다이렉트해야 하는 Angular 빌드 파일을 전개하기 위해 노드 js의 와일드카드 루트를 사용하여 Angular 루트와 노드 js API 루트의 이름 경합이 발생하지 않도록 해야 합니다.

app.module

//Angular App Hosting Production Build
app.use(express.static(__dirname + '/dist/ShoppingCart'));

// For all GET requests, send back index.html (PathLocationStrategy) (Refresh Error)
app.get('*', (req,res) => {
  res.sendFile(path.join(__dirname, '/dist/ShoppingCart/index.html'));
});

const http = require('http');
const fs = require('fs');
var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",
    "js": "text/javascript",
    "css": "text/css"
};

var server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.writeHeader(200, { "Content-Type": "text/html" });
        fs.createReadStream('./public/index.html').pipe(res)
    }
    var filesDepences = req.url.match(/\.js|.css/);
    if (filesDepences) {
         var extetion = mimeTypes[filesDepences[0].toString().split('.')[1]];
        res.writeHead(200, { 'Content-Type': extetion });
        fs.createReadStream(__dirname + "/public" + req.url).pipe(res)
    }
})

server.listen(8080);

언급URL : https://stackoverflow.com/questions/35995273/how-to-run-html-file-using-node-js

반응형