NodeJs入門——ローカルサーバの構築

986 ワード

nodeサーバを作成:
    1.ブラウザポート(httpモジュール)を傍聴する
    2.取得要求のurl
    3.データを返す
//server.js

const http=require('http');

let server=createServer((req,res)=>{
  res.wirte('    ');
  console.log('     ');
  res.end();
})

server.listen(8080)
    サーバがクライアントにデータを返していない場合は、そのままres.end()で返すことができます。
    現在のディレクトリでnode server.jsを実行して、ブラウザで入力します。http://localhost:8080
 
fsモジュールを導入してファイルを読み込みます。
    プロジェクトでwwwフォルダを作成して、読み込むファイルを保存します。
//server2.js

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

let server=createServer((req,res)=>{
  console.log('     ')
  fs.readFile(`www${req.url}`,(err,data)=>{
    if(err){
      res.writeHeaders(404);
      res.write('Not Found');
    }else{
      res.write(data);
    }
    res.end();
  })
});

server.listen(8080)
現在のディレクトリでnode server 2.jsを実行して、ブラウザで入力します。http://localhost:8080/1.html
簡単にNodeローカルサーバーを構築しました。