Process
// Process does not require a "require", it's automatically available.
Exit from a Node program
syntax:
process.exit(<exit_code>)
Exit codes are as follows:
- 0: Success
- 1: Uncaught Fatal Exception
- 2 (Unused) - reserved for bash
- 3: Internal JavaScript Parse Error
- 4: Internal JavaScript Evaluation Failure
- 5: Fatal Error
- 6: Non-function Internal Exception Handler
- 7: Internal Exception Handler Run-Time Failure
- 8 (Unused)
- 9: Invalid Argument
- 10: Internal JavaScript Run-Time Failure
- 12: Invalid Debug Argument
- 13: Unfinished Top-Level Await
- >128: Signal Exits
// calling process.exit(), results in aborigin any currently pending
or running request
Alternatively,
const server = app.listen(3000, () => console.log('Server ready'))
process.on('SIGTERM', () => {
server.close(() => {
console.log('Process terminated')
})
})
Environment Variables
process.env.<env_var>
Express
Express is a framework that uses the http module under the hood,
app.listen() returns an instance of http. You would use
https.createServer if you needed to serve your app using HTTPS, as
app.listen only uses the http module.
Module
Exports
functionality must be exposed before it can be imported by other files. Any other object or variable defined in the file by default is private
There are 2 ways to export property.
| Module.exports | exports |
|---|---|
| exposes the object it points to. | exposes the properties of the object it points to |
|
|
|
|
Events
Event Emitter
/* initialization */
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()
/* callback */
eventEmitter.on('start', () => {
console.log('started')
})
/* trigger event */
eventEmitter.emit('start')
Other methods exposed by EventEmitter
- once(): add a one-time listener
- removeListener() / off(): remove an event listener from an event
- removeAllListeners(): remove all listeners for an event