Coding Guidelines NodeJS
Coding Guidelines NodeJS
$ mkdir my-project
$ cd my-project
$ npm init
2. Setup .npmrc –
If you’ve used npm before, you may have come across the - -save flag
which updates the package.json with the dependency. When other
developers clone the project, they can be sure to have the right
dependencies because of this. Unfortunately, remembering to add the
flag can be a problem.
Now when you run npm install, you can be sure the dependency is saved
and will be locked down to the version you installed.
4. ‘Requires’ at top –
core modules
npm modules
others
1. 4 spaces for indentation - Use 4 spaces for indenting your code or a Tab
2. Newlines - Use UNIX-style newlines (\n), and a newline character as the
last character of a file.
Windows-style newlines (\r\n) are forbidden inside any repository.
3. No trailing white space – Just like you brush your teeth after every meal,
you clean up any trailing white space in your .js files before committing.
Otherwise the rotten smell of careless neglect will eventually drive away
contributors and/or co-workers.
4. 80 characters per line - Limit your lines to 80 characters.
5. Use single quotes - Use single quotes unless you are writing JSON. This
helps you separate your objects’ strings from normal strings.
6. Opening braces go on the same line - Your opening braces go on the
same line as the statement.
if (true) {
console.log(‘winning’);
}
Naming Conventions
Functions
1. Write small functions - Keep your functions short. A good function fits on
a slide that the people in the last row of a big room can comfortably read.
2. Return early from functions - To avoid deep nesting of if-statements,
always return a function’s value as early as possible.
Right:
function isPercentage(val) {
if (val < 0) {
return false;
}
if (val > 100) {
return false;
}
return true;
}
Wrong:
function isPercentage(val) {
if (val >= 0) {
if (val < 100) {
return true;
} else {
return false;
}
} else {
return false;
}
}
3. Method chaining - One method per line should be used if you want to
chain methods. You should also indent these methods so it’s easier to tell
they are part of the same chain.
Logging
Please clean up logs when they are no longer helpful. In particular, logging
the same object over and over again is not helpful. Logs should report what
is happening so that it’s easier to track down where a fault occurs. Use
appropriate log levels.