简体   繁体   中英

Node.JS Express - Importing a folder As A Module

I am new in express.

What I am trying to do is import a folder as a module so that in future I can use other files in the folder can be used as modules.

So, what I have done is change this-

var routes = require('./routes/index');
var users = require('./routes/users');

app.use('/', routes);
app.use('/users', users);

to this-

var routes = require('./routes');

app.use('/', routes.index);
app.use('/users', routes.users);

But I am getting error like this-

在此处输入图片说明

Can anyone please help, what can I do to solve this issue so that I can use all files inside route folder as modules?

Update-

Regarding to @AnubhavSrivastava , my requirement is OK because I have seen this in MVA tutorial. Link is here and time is 1:32:58 .

Code is like this-

在此处输入图片说明

Thanks in advance for helping.

When you do require over a folder, it returns index.js module by default, you wont get route.user, unless you have a variable that is exported in index.js.

Extract from node js official documentation here - https://nodejs.org/api/modules.html#modules_folders_as_modules

Folders as Modules

It is convenient to organize programs and libraries into self-contained directories, and then provide a single entry point to that library. There are three ways in which a folder may be passed to require() as an argument.

The first is to create a package.json file in the root of the folder, which specifies a main module. An example package.json file might look like this:

{ "name" : "some-library", "main" : "./lib/some-library.js" }

If this was in a folder at ./some-library, then require('./some-library') would attempt to load ./some-library/lib/some-library.js.

This is the extent of Node.js's awareness of package.json files.

Note: If the file specified by the "main" entry of package.json is missing and can not be resolved, Node.js will report the entire module as missing with the default error:

Error: Cannot find module 'some-library'

If there is no package.json file present in the directory, then Node.js will attempt to load an index.js or index.node file out of that directory. For example, if there was no package.json file in the above example, then require('./some-library') would attempt to load:

./some-library/index.js
./some-library/index.node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM