0
0

Node.jsのrequire.mainについて

Posted at

require.main

require.moduleは、モジュールオブジェクトで、Node.jsの起動時にロードされたエントリースクリプト表す。

Node実行時のディレクトリが /abusolute/path/to で、app.jsを実行する場合。

entry.js
console.log(require.main);

Node.jsでapp.jsを実行

node entry.js

コンソールへの出力

Module {
  id: '.',
  path: '/absolute/path/to',
  exports: {},
  filename: '/absolute/path/to/entry.js',
  loaded: false,
  children: [],
  paths:
   [ '/absolute/path/to/node_modules',
     '/absolute/path/node_modules',
     '/absolute/node_modules',
     '/node_modules' ] }

require.mainの利用

require.mainで取得できるモジュールオブジェクトの中には、エントリーファイルのpathを表すfilename が含まれている。

これを利用して、Node.jsプロジェクトの実行ディレクトリを取得する記述が以下の通り。
/absolute/path/to/util/path.js

path.js
const path = require('path');

module.exports = path.dirname(require.main.filename);

exportしているので、他のファイルからrequireして利用することができる。
/absolute/path/to/routes/sample.js

sample.js
const path = require('path')
const express = require('express');

const router = express.Router();

// path.jsからexportしたディレクトリを利用
const routeDir = require('../util/path');

// /absolute/path/to/views/sample.htmlを返却
router.get('/',(req, res, next) => {
  res.sendFile(path.join(routeDir, 'views', 'sample.html'))
});

/absolute/path/to/app.js

app.js
const express = require('express')
const bodyParser = require('body-parser')

// add routes
const sampleRoutes = require('./routes/sample');

const app = express();

// add body parser
app.use(bodyParser.urlencoded({extended: false}))

app.use(sampleRoutes);

app.listen(3000);

参考

Node.jsのドキュメントはこちら
https://nodejs.org/api/modules.html#requiremain

0
0
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
0
0