Convenciones de nomenclatura de proyectos de Node.js para archivos y carpetas

What are the naming conventions for files and folders in a large Node.js project?

Should I capitalize, camelCase, or under-score?

Ie. is this considered valid?

project-name
    app
        controllers
            someThings.js
            users.js
        models
                someThing.js
                user.js
        views
            some-things
                index.jade
            users
                logIn.jade
                signUp.jade
    ...

preguntado el 21 de septiembre de 13 a las 00:09

Highly subjective, your directory structure is your own. Personally I like to camelCase since that is what I do in JS -

@Chad - in Node.js, require takes the directory string as a parameter, which is why it's not enteramente your own. ie. require('../app/controllers/someThings'); -

Node doesn't specify any suggestions or standards for naming modules, just as long as they're valid file/directory names and don't try to override core module names. For its own modules, it uses a mixture of abbreviated (fs), single-word (events), underscored (child_process), and lowercase (querystring). -

@Rudiger So? You can specify whatever string you want, and directory structure you want you can have (provided your names are valid file names of course). -

From what I can tell from poking around the more keystone projects like moca file names like captain-awesome-file.js seem to be common enough. That's what I am going to use at least! -

8 Respuestas

After some years with node, I can say that there are no conventions for the directory/file structure. However most (professional) express applications use a setup like:

/
  /bin - scripts, helpers, binaries
  /lib - your application
  /config - your configuration
  /public - your public files
  /test - your tests

An example which uses this setup is nodejs-starter.

I personally changed this setup to:

/
  /etc - contains configuration
  /app - front-end javascript files
    /config - loads config
    /models - loads models
  /bin - helper scripts
  /lib - back-end express files
    /config - loads config to app.settings
    /models - loads mongoose models
    /routes - sets up app.get('..')...
  /srv - contains public files
  /usr - contains templates
  /test - contains test files

In my opinion, the latter matches better with the Unix-style directory structure (whereas the former mixes this up a bit).

I also like this pattern to separate files:

lib/index.js

var http = require('http');
var express = require('express');

var app = express();

app.server = http.createServer(app);

require('./config')(app);

require('./models')(app);

require('./routes')(app);

app.server.listen(app.settings.port);

module.exports = app;

lib/static/index.js

var express = require('express');

module.exports = function(app) {

  app.use(express.static(app.settings.static.path));

};

This allows decoupling neatly all source code without having to bother dependencies. A really good solution for fighting nasty Javascript. A real-world example is cerca which uses this setup.

Update (filenames):

Regarding filenames most common are Corto, minúscula filenames. If your file can only be described with two words most JavaScript projects use an underscore as the delimiter.

Update (variables):

Regarding variables, the same "rules" apply as for filenames. Prototypes or classes, however, should use el caso de Carmel.

Update (styleguides):

Respondido 03 Oct 19, 09:10

How interesting and well done is your answer, it's off topic, the topic creator specifically asked for naming convention not for directory structures. When we get to this topic, we expect to know if files are better named with dashes, underscores or camelCase. I will upvote, if this is added to this answer. - tronix117

@Tronix117 what is the problem? The question asks for "project naming conventions for files & folders?" and naming is not limited to the file name as it also includes the complete path name. - Bodokaiser

of course, but the author specifically ask "Should I capitalize, camelCase, or under-score?". When he write his exemple, he explicitly put 'someThings' and 'some-things' just to know if it can be considered as valid. When I went to this topic I was expecting to have the answer to this specific question, and to know what is usually used as file naming. I don't say your answer is wrong, it's perfect for its purpose, but incomplete in my mind because he doesn't really answer the main question. - tronix117

I think you misunderstood me ;). I was just looking for something that I didn't found on the accepted answer, but was specifically asked, not spreading hate in any kind, you're going a bit far on this one. I just wanted you to add some informations about that on the answer, so that people who will look for that in the future will not get in a dead-end. - tronix117

@Tronix117 Actually, this is specifically why I found myself on this page reading this answer. I was hoping for not only directory structure, but more importantly name conventions (dashes, underscores, camelCase, TitleCase, etc...). Unfortunately, the answer still does not contain it, and it seems bodokaiser is taking things too personally for me to jump in and request that his opinion regarding this be added to his answer (as the OP initially asked in their question) (tos tos). - Girar

Utilice las kebab-case for all package, folder and file names.

¿Por qué?

You should imagine that any folder or file might be extracted to its own package some day. Packages cannot contain uppercase letters.

New packages must not have uppercase letters in the name. https://docs.npmjs.com/files/package.json#name

Por lo tanto, camelCase should never be used. This leaves snake_case y kebab-case.

kebab-case is by far the most common convention today. The only use of underscores is for internal node packages, and this is simply a convention from the early days.

Respondido 03 Jul 17, 10:07

you forgot dot? like socket.io - hueva

.2c, could do a simple automation from kebab-case to kebabCase in any script or app in any language using regex -- do it all the time 🙃 - robar2d

node_modules is the reason I'll stick with snake case. - basura polvorienta

@dustytrash There are other common files which use the kebab-case like package-lock.json or service-worker.ts. - Spenhouet

Exactly, the only thing I do not like about kebab case is when I edit the file name, if I double click, it does not select all the file name, so maybe snake case is good, all about preference ofcourse - onuriltan

There are no conventions. There are some logical structure.

The only one thing that I can say: Never use camelCase file and directory names. Why? It works but on Mac and Windows there are no different between someAction and some action. I met this problem, and not once. I require'd a file like this:

var isHidden = require('./lib/isHidden');

But sadly I created a file with full of lowercase: lib/ishidden.js. It worked for me on mac. It worked fine on mac of my co-worker. Tests run without errors. After deploy we got a huge error:

Error: Cannot find module './lib/isHidden'

Oh yeah. It's a linux box. So camelCase directory structure could be dangerous. It's enough for a colleague who is developing on Windows or Mac.

So use underscore (_) or dash (-) separator if you need.

Respondido el 04 de enero de 14 a las 22:01

+1, add the fact that renaming case-sensitive folders in git on a non-cs system is a real hassle. - max

I don't really understand the problem with camelCase here. Wouldn't the issue be resolved by naming the file correctly in the first place (lib/isHidden.js)? - Mike

Hey Mike, the point is that camelCase is going to break on deployment on some systems. I was confused about why my directories were all getting 404s when I deployed from Mac onto a Linux box with a package named "groupPages". I had to change to group-pages to fix things. - tempranova

Worse yet: create a camelcase version of a file name and have a careless colleague create a lowercase version in the same directory. Now do a check out in a non-case-sensitive os, and try to figure out why the hell your application isn't working. And yes, this happened. - L0LN1NJ4

I like this answer, however I want to point that dash (-) may have some problems too. For example, using Nighwatch test framework I created a page object named admin-login.js. Then I tried to access it from the test script using const loginPage = browser.page.admin-login(). I got error ReferenceError: login is not defined. Using underscore (_) for the file name solved the problem. I can also imagine that using filenames with dash character in command line can also lead to some problems. Therefore, I'd say that underscore is safest separator for file names in general. - Dragan Nikolic

Based on 'Guía de estilo de JavaScript de Google'

File names must be all lowercase and may include underscores (_) or dashes (-), but no additional punctuation. Follow the convention that your project uses. Filenames’ extension must be .js.

Respondido 04 Abr '18, 16:04

Node.js doesn't enforce any file naming conventions (except index.js). And the Javascript language in general doesn't either. You can find dozens of threads here which suggest camelCase, hyphens and underscores, any of which work perfectly well. So its up to you. Choose one and stick with it.

Respondido el 31 de diciembre de 13 a las 21:12

It is not actually what node 'enforces', please read this: nodejs.org/api/modules.html#modules_folders_as_modules - moca

index.js is not a naming convention lol. Index js, I am pretty sure, originates back from why every was server based HTML (I was a kid then) but it use to be, when I was 8 or 9 (and yes I wrote HTML at 8 or 9, I mean it was HTML, and it was simple to what we have today) anyway... and it use to be that at the root of the project was an index.html file that actually contained an index of all html files included in the website. I remember that this was an old method for doing things even back in 1995/1996, but that's how sites started out. - JΛYDΞV

According to me: For files, use lower camel case if module.exports is an object, I mean a singleton module. This is also applicable to JSON files as they are also in a way single ton. Use upper camel case if module.exports returns a constructor function where it acts like a class.

For folders use short names. If there is need to have multiple words, let it be completely lower case separated by "-" so that it works across all platforms consistently.

Respondido 02 Abr '17, 11:04

Esta es mi idea

project-name
    app
        controllers
            somethings.controller.js
            user-story.controller.js
            users.controller.js
        models
                something.model.js
                user.model.js
        views
            some-things
                index.view.jade
            users
                login.view.jade
                signup.view.jade

respondido 12 mar '22, 15:03

This idea of multiple dots is worth taking a closer look at: since we do not need to specify the file ending for require("something"), we can create our own app- or framework-specific naming convention for what to put after the first period: in the example const login = require("login.view") can emphasize that the default export of that file is probablemente a View-shaped object. I like this, perhaps it can save a few levels of subdirectories too. - conny

La mayoría de la gente usa camelCase in JS. If you want to open-source anything, I suggest you to use this one :-)

Respondido el 01 de enero de 14 a las 18:01

Some projects, such as Locomotive.js are using camelCase for controller files. :-) Just depends. I tend to use PascalCase for class-like files. - Mathieu Amiot

@yitsushi seems to raise quite a concern with camel (and pascal) case naming, if you want to create portable modules camel case surely seems a bad idea? - gomaflux

Yea, camel case is a bad idea as many 3rd party libraries, APIs, modules, frameworks(especially frameworks) will parse your package, and it will assume that the filenames are in kebob format, and code is in camelcase. - JΛYDΞV

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.