7
7

More than 5 years have passed since last update.

Express から NPM をフロントエンドに expose する

Last updated at Posted at 2014-07-15

browserify とか導入するのが面倒な時に。

バックエンド側:

var fs = require('fs');
var path = require('path');
var express = require('express');

app = express();

app.get('/node_modules/:name', function (req, res) {
  var dir = path.resolve('node_modules', req.params.name);
  fs.readFile(path.join(dir, 'package.json'), { encoding: 'utf8' }, function (err, data) {
    if (err) throw err;
    var pkg = global.JSON.parse(data);
    fs.readFile(path.join(dir, pkg.main), { encoding: 'utf8' }, function (err, data) {
      if (err) throw err;
      res.setHeader('Content-Type', 'text/javascript; charset=UTF-8');
      res.send(data);
    });
  });
});

app.listen();

フロントエンド側 HTML:

<script src="/node_modules/d3" charset="UTF-8"></script>
<script>
  console.log(d3.version);
  // -> 3.4.8
<script>
7
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
7
7