Question:
I'm creating a file structure in an application where each directory contains an "index" file. This index file takes the name of my directory to improve readability. Ex:
foo
|--foo.js // <- index
|--bin.html
|--bar
| |--bar.js // <- index
|--bin.html
With that, the structure that will be used for a require()
when importing any file will always be something like
const foo = require('./foo/foo');
const bar = require('./foo/bar/bar');
I'm looking for some way to create a file without the naming, and that NodeJS understands for the import, it would be something like:
foo
|--.js // <- sem nome = arquivo da pasta
|--bin.html
So I could work with files similar to namespace's…
Is there any way to do this with NodeJS?
Answer:
You can use foo/index.js
and require('./foo')
(this is more prudent and quite common). Or you can add a package.json
to the foo
directory and give the main
any name.
eg.
foo/package.json
{"main": "qualquer-coisa.js"}
main.js
require('./foo') // vai dar require em './foo/qualquer-coisa.js'
The complete algorithm is at: https://nodejs.org/api/modules.html#modules_folders_as_modules
But it doesn't do that , it does n't go with the conventions much.
better just do
foo
|--index.js
|--bin.html
require('./foo')