Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8691

Node.jsでExpress.jsを使ってpng画像を動的に表示するサンプル

$
0
0

画像ファイルを動的に表示するコードです。なかなか見つからなかったのでメモしておきます。

express.js
constexpress=require('express');constfs=require('fs');constapp=express();app.get('/image',(req,res)=>{console.log('image');fs.readFile('./example.png',(err,data)=>{res.type('png');res.send(data);});});app.listen('3000',()=>{console.log('Application started');});

スクリプトを実行し

% node express.js
Application started
image

ブラウザで下記URLにアクセスすると画像が表示されます
http://localhost:3000/image

スクリーンショット 2020-08-25 12.40.21.png

ちなみにディレクトリのファイル一覧はこんな感じです

% ls
example.png     package-lock.json
express.js      package.json
node_modules

Viewing all articles
Browse latest Browse all 8691

Trending Articles