nprogram’s blog

気ままに、プログラミングのトピックについて書いていきます

node, npm, node_staticを用いて、とっても簡単に画像を表示しましょう

はじめに

ソースコードGitHubに上げました。 github.com

ソースコードの動かし方は、README.mdに記載しましたので、よろしければご確認ください。

環境

ディレクトリ構成

f:id:nprogram:20161106232102p:plain

説明

index.jsソースコードのみで、サーバーが起動できます。

[index.js]

var static = require('node-static');

//
// Create a node-static server instance to serve the './public' folder
//
var file = new static.Server('./public');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        //
        // Serve files!
        //
        file.serve(request, response);
    }).resume();
}).listen(8080);

node index.jsコマンドを入力して、

http://localhost:8080/images/test.jpgにアクセスすることで、

画像が表示されます。