Nodejs syntax - davidkhala/node-utils GitHub Wiki
- require('node:fs') vs require('fs')
- When to use classic function or arrow function
- [assert] to assert a value should be null, use
assert.ifError(value)
- Optional_chaining
obj?.propKey
is allowed if obj is undefined- Introduced in Nodejs 14
- support for .env files.
- Experimental in Node.js 20
Build CLI binary by nodejs
- use shebang
#!/usr/bin/env node
in nodejs source code - References
- use nexe if you want to
- skip prerequisite of nodejs installation
- accept python3 as environment dependency for use nexe
Regular Expression (Regex)
- If you need to know if a string matches a regular expression RegExp, use RegExp.prototype.test().
- If you only want the first match found, you might want to use RegExp.prototype.exec() instead.
- If you want to obtain capture groups and the global flag is set, you need to use RegExp.prototype.exec() or String.prototype.matchAll() instead.
- String.prototype.match() won't return groups if the /.../g flag is set. However, you can still use String.prototype.matchAll() to get all matches.
- If you want to match a repeated pattern (e.g. substring) but don't want to have it in captured group, use Non-capturing-group syntax
(?:pattern)
- Most of the regular expression engines use backtracking to try all possible execution paths of the regular expression when evaluating an input, in some cases it can cause performance issues, called catastrophic backtracking situations. In the worst case, the complexity of the regular expression is exponential in the size of the input, this means that a small carefully-crafted input (like 20 chars) can trigger catastrophic backtracking and cause a denial of service of the application. Super-linear regex complexity can lead to the same impact too with, in this case, a large carefully-crafted input (thousands chars).
Running TypeScript Natively
You can write code that's valid TypeScript directly in Node.js without the need to transpile it first.
From v23.6.0 onwards, type stripping is enabled by default