6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-08-25

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

express.js

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

const app = 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
6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?