Node v12.3.0 (Current)

Node v12.3.0 (Current)

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

Notable changes

  • esm:
  • Added the --experimental-wasm-modules flag to support WebAssembly modules (Myles Borins & Guy Bedford) #27659
  • process:
  • Log errors using util.inspect in case of fatal exceptions (Ruben Bridgewater) #27243
  • repl:
  • Add process.on('uncaughtException') support (Ruben Bridgewater) #27151
  • stream:
  • Implemented Readable.from async iterator utility (Guy Bedford) #27660
  • tls:
  • Expose built-in root certificates (Ben Noordhuis) #26415
  • Support net.Server options (Luigi Pinca) #27665
  • Expose keylog event on TLSSocket (Alba Mendez) #27654
  • worker:
  • Added the ability to unshift messages from the MessagePort (Anna Henningsen) #27294

Commits

  • [7cc21d8afa] - assert: remove unused code (Ruben Bridgewater) #27676
  • [6983a0c336] - assert: add compatibility for older Node.js versions (Ruben Bridgewater) #27672
  • [493ead144d] - assert: loose deep equal should not compare symbol properties (Ruben Bridgewater) #27653
  • [ec642f18cc] - assert: use less read operations (Ruben Bridgewater) #27525
  • [3367bad080] - assert: refine assertion message (Ruben Bridgewater) #27525
  • [e573c99bfd] - assert: fix assert.fail() stack (Ruben Bridgewater) #27525
  • [6070e8872d] - async_hooks: don't reuse resource in HttpAgent (Gerhard Stoebich) #27581
  • [e74e661044] - async_hooks: only disable promise hook if wanted (Anna Henningsen) #27590
  • [026bebfcbc] - bootstrap: --frozen-intrinsics unfreeze console (Guy Bedford) #27663
  • [e0589006a8] - build: add arm64 to vcbuild.bat help message (Jon Kunkee) #27683
  • [766a731137] - build: export OpenSSL UI symbols (Sam Roberts) #27586
  • [2bc177aa4f] - child_process: setup stdio on error when possible (cjihrig) #27696
  • [b380c0f311] - child_process: refactor stdioStringToArray function (zero1five) #27657
  • [da102cda54] - console: don't attach unnecessary error handlers (cjihrig) #27691
  • [83f243038f] - deps: V8: cherry-pick cca9ae3c9a (Benedikt Meurer) #27729
  • [750556dcfd] - deps: update OpenSSL configs' timestamps (Jon Kunkee) #27544
  • [314fdda0c3] - deps: regenerate OpenSSL configs with fixed tooling (Jon Kunkee) #27544
  • [c7e5fca32c] - deps: make VC-WIN config generation deterministic (Jon Kunkee) #27543
  • [76c9e86609] - deps: patch V8 to 7.4.288.27 (Matheus Marchini) #27615
  • [9f5b6900e7] - doc: corrected tlsSocket.getPeerCertificate response type (Dan Beglin) #27757
  • [d1da11765d] - doc: correct parameter type on 'subprocess.kill([signal])' (himself65) #27760
  • [7e750868c6] - doc: replace createRequireFromPath() references (cjihrig) #27762
  • [55fe340dc2] - doc: improve createRequire() example (cjihrig) #27762
  • [378f44c2ed] - doc: update util.format formatters documentation (Ruben Bridgewater) #27621
  • [f663e74d0b] - doc: remove stability highlight for stable functions (Michael Dawson) #27753
  • [cf516f7b6a] - doc: rewrite "About this Documentation" section (Rich Trott) #27725
  • [df01645c7c] - doc: correct entry for electron v4.0.4 (Jacob) #27394
  • [1f7a527f04] - doc: clarify behavior of fs.mkdir (Gaelan) #27505
  • [d570995427] - doc: remove non-existent entry-type flag (dnalborczyk) #27678
  • [da4a3797cb] - doc: format correction for experimental loader hooks (Daniel Nalborczyk) #27537
  • [cc45080109] - doc: dns.lookup() documentation error code (jvelezpo) #27625
  • [7923b4a407] - doc: add call-once note to napi_queue_async_work (Gabriel Schulhof) #27582
  • [8d448be9fd] - doc: simplify test/README.md (Rich Trott) #27630
  • [172fa639a6] - doc: simplify About This Documentation text (Rich Trott) #27619
  • [66cf89f57d] - doc: move Rod Vagg to TSC emeritus (Rod Vagg) #27633
  • [8a1f2d0bfc] - doc: doc deprecate the legacy http parser (cjihrig) #27498
  • [a23e86f029] - doc: add Sam Roberts to TSC (Rod Vagg) #27606
  • [c53a674be7] - doc: add example to test doc for clarity (Aditya Pratap Singh) #27561
  • [c0cdf30e6e] - doc: improve CCM example (Tobias Nießen) #27396
  • [b5498ed19b] - doc,meta: codify security release commit message (Richard Lau) #27643
  • [6e2c8d0e18] - doc,n-api: update N-API version matrix for v12.x (Richard Lau) #27745
  • [767889b0a3] - doc,n-api: fix introduced\_in metadata (Richard Lau) #27745
  • [4ed8a9ba7e] - doc,tools: updates for 6.x End-of-Life (Richard Lau) #27658
  • [80f30741bd] - esm: use correct error arguments (cjihrig) #27763
  • [47f913bedc] - (SEMVER-MINOR) esm: --experimental-wasm-modules integration support (Myles Borins) #27659
  • [89fda94b6a] - esm: fix esm load bug (ZYSzys) #25491
  • [1f935f899f] - events: improve max listeners warning (Ruben Bridgewater) #27694
  • [6f23816bcf] - fs: extract path conversion and validation to getValidatedPath (ZYSzys) #27656
  • [206ae31a7e] - http: always call response.write() callback (Luigi Pinca) #27709
  • [bfb9356942] - http: do not default to chunked encoding for TRACE (Luigi Pinca) #27673
  • [4a9af1778d] - http: add an alias at addListener on Server connection socket (himself65) #27325
  • [a66b391d20] - http2: do no throw in writeHead if state.closed (Matteo Collina) #27682
  • [74046cee72] - http2: do not override the allowHalfOpen option (Luigi Pinca) #27623
  • [c7461567ce] - inspector: mark profile type const (gengjiawen) #27712
  • [24b26c0687] - inspector: fix typo (gengjiawen) #27712
  • [700459e008] - inspector: added NodeRuntime domain (Aleksei Koziatinskii) #27600
  • [d2d3bf8b3b] - inspector: code cleanup (Eugene Ostroukhov) #27591
  • [4dbebfd464] - lib: fix typo in pre_execution.js (gengjiawen) #27649
  • [88b4d00fc6] - lib: restore global.module after --eval code is run (Anna Henningsen) #27587
  • [3ac4a7122b] - meta: move jhamhader to Collaborator Emeriti list (Rich Trott) #27707
  • [9f9871c4b2] - meta: move chrisdickinson to Collaborator Emeriti list (Rich Trott) #27703
  • [2e85642f4a] - meta: move whitlockjc to Collaborator Emeriti list (Rich Trott) #27702
  • [fc8ad7731f] - meta: move estliberitas to Collaborator Emeriti list (Rich Trott) #27697
  • [ea62149212] - meta: move firedfox to Collaborator Emeriti list (Rich Trott) #27618
  • [6bef4c0083] - meta: move AnnaMag to Collaborator Emeriti list (Rich Trott) #27603
  • [14d58c2f95] - meta: move pmq20 to Collaborator Emeriti list (Rich Trott) #27602
  • [876441eefb] - meta: move orangemocha to Collaborator Emeriti list (Rich Trott) #27626
  • [140b44f3ea] - module: fix createRequireFromPath() slash logic (cjihrig) #27634
  • [8a96182827] - module: add missing space in error message (cjihrig) #27627
  • [c33e83497e] - module: simplify createRequire() validation (cjihrig) #27629
  • [119a590f84] - module: improve resolve paths validation (cjihrig) #27613
  • [2f512e32a7] - module: handle relative paths in resolve paths (cjihrig) #27598
  • [74feb0b81e] - process: mark process.env as side-effect-free (Anna Henningsen) #27684
  • [0393045198] - (SEMVER-MINOR) process: inspect error in case of a fatal exception (Ruben Bridgewater) #27243
  • [688a0bd2b8] - repl: do not run --eval code if there is none (Anna Henningsen) #27587
  • [c78de13238] - (SEMVER-MINOR) repl: handle uncaughtException properly (Ruben Bridgewater) #27151
  • [d21e066f5a] - src: update UNREACHABLE macro to take a string (Nitish Sakhawalkar) #26502
  • [ae8b64df78] - src: remove util-inl.h from header files (Sam Roberts) #27631
  • [e736e20e87] - src: declare unused priv argument (Sam Roberts) #27631
  • [d2e1efe8a3] - src: fix warnings about redefined BSWAP macros (Sam Roberts) #27631
  • [3c707976da] - src: remove extra semicolons after macros (gengjiawen) #27579
  • [a18692c4df] - src: extract common macro to util.h (gengjiawen) #27512
  • [f6642e90b2] - src: elevate namespaces in node_worker.cc (Preveen Padmanabhan) #27568
  • [62fe3422fb] - src: refactor deprecated UVException usage in pipe-wrap.cc (gengjiawen) #27562
  • [b338d53916] - src: fix typos (gengjiawen) #27580
  • [32fd0ac901] - stream: use readableObjectMode public api for js stream (Anto Aravinth) #27655
  • [05c3d53ecc] - (SEMVER-MINOR) stream: implement Readable.from async iterator utility (Guy Bedford) #27660
  • [f872210ffd] - test: relax check in verify-graph (Gerhard Stoebich) #27742
  • [8b4101a97f] - test: un-mark worker syntax error tests as flaky (Anna Henningsen) #27705
  • [1757250997] - test: clearing require cache crashes esm loader (Antoine du HAMEL) #25491
  • [7252a64a23] - test: pass null params to napi_xxx_property() (Octavian Soldea) #27628
  • [9ed5882dec] - test: use common.PORT instead of an extraneous variable (Benjamin Ki) #27565
  • [f01183c29a] - test: move dgram invalid host test to internet tests (Benjamin Ki) #27565
  • [8cba1affe3] - test: better assertion for async hook tests (Ali Ijaz Sheikh) #27601
  • [0c7f18ebd3] - test: test error when breakOnSigint is not a boolean for evaluate (Ruwan Geeganage) #27503
  • [3801859032] - test: add tests for hasItems method in FreeList (Ruwan Geeganage) #27588
  • [691866f124] - test: fix test-linux-perf flakiness (Matheus Marchini) #27615
  • [d7fcd75f62] - test: remove unneeded --expose-internals (Rich Trott) #27608
  • [815a95734e] - test: refactor test-tls-enable-trace-cli.js (cjihrig) #27553
  • [b6e540a9a2] - test: fix flaky test-tls-multiple-cas-as-string (Luigi Pinca) #27569
  • [a5dab9e85a] - test: deflake test-tls-js-stream (Luigi Pinca) #27478
  • [bdd75d0622] - (SEMVER-MINOR) tls: expose built-in root certificates (Ben Noordhuis) #26415
  • [e61823c43a] - (SEMVER-MINOR) tls: support net.Server options (Luigi Pinca) #27665
  • [eb1f4e50c7] - (SEMVER-MINOR) tls: expose keylog event on TLSSocket (Alba Mendez) #27654
  • [6624f802d9] - tls: fix createSecureContext() cipher list filter (Sam Roberts) #27614
  • [b8b02c35ee] - tls: add missing 'new' (cjihrig) #27614
  • [a8a11862e0] - tools: update markdown linter for Windows line endings (Rich Trott) #27756
  • [c3d16756f2] - tools: remove unneeded dependency files (Rich Trott) #27730
  • [0db846f734] - tools: refactor js2c.py for maximal Python3 compatibility (Refael Ackermann) #25518
  • [0e16b352b4] - tools: decrease code duplication for isString() in lint rules (cjihrig) #27719
  • [47184d1a0a] - tools: update capitalized-comments eslint rule (Ruben Bridgewater) #27675
  • [ea62f4a820] - tools: update dmn to 2.2.2 (Rich Trott) #27686
  • [d2dad0b4b8] - tools: DRY isRequireCall() in lint rules (cjihrig) #27680
  • [1b8bc77990] - tools: add 12.x to alternative docs versions (Richard Lau) #27658
  • [1365683c23] - tools: allow RegExp in required-modules eslint rule (Richard Lau) #27647
  • [169ddc5097] - tools: force common be required before any other modules (ZYSzys) #27650
  • [c6ab6b279c] - tools: enable block-scoped-var eslint rule (Roman Reiss) #27616
  • [fd823ea7a8] - tools: enable camelcase linting in tools (Rich Trott) #27607
  • [217e6b5a06] - tools: switch to camelcasing in apilinks.js (Rich Trott) #27607
  • [10b4a8103d] - util: if present, fallback to toString using the %s formatter (Ruben Bridgewater) #27621
  • [5205902762] - util: remove outdated comment (Ruben Bridgewater) #27733
  • [099c9ce1a1] - util: unify constructor inspection in util.inspect (Ruben Bridgewater) #27733
  • [d8b48675a7] - util: simplify inspection limit handling (Ruben Bridgewater) #27733
  • [6984ca1c2f] - util: reconstruct constructor in more cases (Ruben Bridgewater) #27668
  • [8f48edd28f] - vm: mark global proxy as side-effect-free (Anna Henningsen) #27523
  • [c7cf8d9b74] - (SEMVER-MINOR) worker: add ability to unshift message from MessagePort (Anna Henningsen) #27294
  • [e004d427ce] - worker: use special message as MessagePort close command (Anna Henningsen) #27705
  • [b7ed4d7187] - worker: move receiving\_messages\_ field to MessagePort (Anna Henningsen) #27705

Windows 32-bit Installer: https://nodejs.org/dist/v12.3.0/node-v12.3.0-x86.msi

Windows 64-bit Installer: https://nodejs.org/dist/v12.3.0/node-v12.3.0-x64.msi

Windows 32-bit Binary: https://nodejs.org/dist/v12.3.0/win-x86/node.exe

Windows 64-bit Binary: https://nodejs.org/dist/v12.3.0/win-x64/node.exe

macOS 64-bit Installer: https://nodejs.org/dist/v12.3.0/node-v12.3.0.pkg

macOS 64-bit Binary: https://nodejs.org/dist/v12.3.0/node-v12.3.0-darwin-x64.tar.gz

Linux 64-bit Binary: https://nodejs.org/dist/v12.3.0/node-v12.3.0-linux-x64.tar.xz

Linux PPC LE 64-bit Binary: https://nodejs.org/dist/v12.3.0/node-v12.3.0-linux-ppc64le.tar.xz

Linux s390x 64-bit Binary: https://nodejs.org/dist/v12.3.0/node-v12.3.0-linux-s390x.tar.xz

AIX 64-bit Binary: https://nodejs.org/dist/v12.3.0/node-v12.3.0-aix-ppc64.tar.gz

SmartOS 64-bit Binary: https://nodejs.org/dist/v12.3.0/node-v12.3.0-sunos-x64.tar.xz

ARMv7 32-bit Binary: https://nodejs.org/dist/v12.3.0/node-v12.3.0-linux-armv7l.tar.xz

ARMv8 64-bit Binary: https://nodejs.org/dist/v12.3.0/node-v12.3.0-linux-arm64.tar.xz

Source Code: https://nodejs.org/dist/v12.3.0/node-v12.3.0.tar.gz

Other release files: https://nodejs.org/dist/v12.3.0/

Documentation: https://nodejs.org/docs/v12.3.0/api/

SHASUMS

-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 ad994e17d12427dfb96b796c8a390af14541499edea9cc4b7349305ae650597c node-v12.3.0-aix-ppc64.tar.gz 4a9faa038fb4e6e930a0fecd9818a4820b4ca91d1c45a1c1279fe49cdbd28160 node-v12.3.0-darwin-x64.tar.gz fe1dbbb65d38ef3da56e93197d90d1a1bccc181053913f80efac11832a27447b node-v12.3.0-darwin-x64.tar.xz 66a313ef7d943103fd175e83e8c8a2cccc331f784a54e38bff29240e995c180f node-v12.3.0-headers.tar.gz ea0e98a1c5c2f95df9388e08bd6b58fa40daf3afb34ad6a82282ed8738787fbb node-v12.3.0-headers.tar.xz ffb57ec86f4f279e75e755515fb74149702f3467c4841c47c18cfb5d89e67c6d node-v12.3.0-linux-arm64.tar.gz 3d6e7046b938ff1f2535bdcc892a82abf44d875d1e96779cc3ea9a074ccfa200 node-v12.3.0-linux-arm64.tar.xz c3824e14b88d04f4e2593e2512958b96c58221be79c3308b1b9d9b2d0c7f3ccf node-v12.3.0-linux-armv7l.tar.gz caf85dcaf85a2fd6d099ce9abaf1fd81e83897873ddf04d58df0449e3e5dcea5 node-v12.3.0-linux-armv7l.tar.xz 5d5a2a71169e60b433e8c648fe9d80533184b24c661042d1bdd44ac97239d2b5 node-v12.3.0-linux-ppc64le.tar.gz 74a0a208820072621402f06ef462e5f53585a7f77a364a40e9f9c4479a2390a7 node-v12.3.0-linux-ppc64le.tar.xz 7fa7adc4121d3102f9744770a37bf1f57568a8a5d033ecb5c095a3d67f965450 node-v12.3.0-linux-s390x.tar.gz a6ae7ed30851b15c74f5da0dbacb876de26b79db23c73e6915a27df695a3bdef node-v12.3.0-linux-s390x.tar.xz 1159739eb0e77d874bcbb59809b504c790ff275506c7a855dd8cabb495e93cc1 node-v12.3.0-linux-x64.tar.gz 2ce2c7a4d7fe3c560415e8dcbc5905a66a8bf28e2a2b2cff7e7a4eeb5753015d node-v12.3.0-linux-x64.tar.xz 42f6fb6fdcbef00bde25fad8c5883a7688bee9a0dfb56191edbde66beb4436c0 node-v12.3.0-sunos-x64.tar.gz 3d59bfcf196defcdd54c1b8b52bc1f6337384db2e4fc93a0d00826db95c3c3cb node-v12.3.0-sunos-x64.tar.xz 53f810c5fe35a8cf95afba72ceda8bb1d7ea29b81db119f55f7344e83de94abb node-v12.3.0-win-x64.7z b36c9f9809c90ce704465f066861314d6e33176a5d45da14c1519c3e4f35063e node-v12.3.0-win-x64.zip dbf2cd9f23915d24c82046888612c6ed944373f9c957ff56e0309b8748af3a3f node-v12.3.0-win-x86.7z 068f514effbb680e71c90ee2b72cb788fb28ce4a8fd4bc209e8695fba0a28e1c node-v12.3.0-win-x86.zip 9c82a9137d0d481429c1df16c83c487d835a010f05bc2439baaf00da86d8e6ec node-v12.3.0-x64.msi e033e87144578f16e017e6c040e4dd9d94d3c1d148e0e6061387ac0af3969790 node-v12.3.0-x86.msi 7b8321e0f48ce6a9d0975bf1bb4ce902b4fdba85026c235b8d681e9df744bcbd node-v12.3.0.pkg e26c54677964cb6b242a6221f3c121620564718f8be1e9a36a16f69860c575ea node-v12.3.0.tar.gz dc5e3eb2dabc38b31a7454a4426e852b9dbbb9b72722eedaa0d0e3d4fde2fd04 node-v12.3.0.tar.xz bdec7c59c23e53b772af758b0bd2ceff588ce7b74afb770ceee1d012e7e6d23a win-x64/node.exe bd8ac8d42c9eccba3f8936522e2f814d60e9f455d14a0f14f01a8bde6213dbed win-x64/node.lib cb36ca5fdcb698234bb0de0f9b549f69164d4d769ae504c8ce04b4c21553cd1c win-x64/node_pdb.7z 4a9cebad325a6149e5742352ba48f0c19044ee744c1a589c06bf44131af0ce55 win-x64/node_pdb.zip a41bbb08154c7b44cf615146e11706c5db221369ad7b963c0b99acf9bb48c3a4 win-x86/node.exe 5b8b66716002053a1c80c41ca80f9c5a7212715f5bfac6e4d421eb11f7f662c1 win-x86/node.lib 1a3172d7ff28fed8d15fbf8d5ad8a934dc1dec8a32caf576ff4cc41681d8a148 win-x86/node_pdb.7z 5d03d5033283c93069b3bf4f2935b352c5ae59ef61b482b9b68eaa063ceae762 win-x86/node_pdb.zip -----BEGIN PGP SIGNATURE----- iQIzBAEBCAAdFiEEpIwr7mgOhBYyzU5E8HSWs+s8F2IFAlzkUPcACgkQ8HSWs+s8 F2IM/hAArzgtHjU6c3UR4Hd8GK55DbUJpCRVQHjHsz19xoCjTTVmRMMElaqjPCR1 PWxZFqqtVq2g8UVHd8sAlpPOVMxVGycdRMHFJHQQ9DxxpXH2f8wSyHPMidWnXfBR GO71RM/7C/F/p2m3olVMLWaKg3RBZ0C0qIo6YKne/TjVSH50ukFLfwSZkGFDcgbT Zim35Zky0LKwapgbn2t30mi87x4ZzVGRq5Rqx1n3gch1w0kRbpD9y6zpE9JTRbLu WEpbPvGSJzsKiDGhvQnRGtoN1qvwAncoUeHoEnyRVrzaCoQpY4tgWRLf8GWGIKX5 rebc5F8OGxJNKpWMKUS5CAw9I73Fto80PO812RxxbATV7o5rqm/KXxnBF/bV6Tt8 q+vWTcPnq7Vf4OJPIL7doub65gv3fpY/Fau3qG7yjnQYja0vMLeAkwpYhO3ux/r1 A1FyJi/rlaKvAy28q+X22dYS9HqjBZQAWeou3wpo91jITDfGHl20ygHTQXMueQKA grIEbeo/518Rji+/fjPbxWxfju0usmYN6BW8lycCf295oMFvh4YJpcEbw0OLxY/i JETx/+Lmhf3/VkngudRxICDWmwvuinueWMGwVJ5N/Oat7ZdAIqlk/Tne7taLPL5H GZZln6Bh65lmx09VptQkglUJ15dDaCesXS9KMe/JqbvmtRWlQJE= =NfEz -----END PGP SIGNATURE-----


Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Node.js: The Complete Guide to Build RESTful APIs (2018)

Database Caching With Redis and Java

Using Redis Cache with Nodejs to make application super fast

Top 10 Node.js Frameworks

How To Build a Node.js Application with Docker

An introduction to Web Development with Rust for Node.js Developers


How to Use Express.js, Node.js and MongoDB.js

How to Use Express.js, Node.js and MongoDB.js

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

Creating a Node Application

To get started I would recommend creating a new database that will contain our application. For this demo I am creating a directory called node-demo. After creating the directory you will need to change into that directory.

mkdir node-demo
cd node-demo

Once we are in the directory we will need to create an application and we can do this by running the command
npm init

This will ask you a series of questions. Here are the answers I gave to the prompts.

The first step is to create a file that will contain our code for our Node.js server.

touch app.js

In our app.js we are going to add the following code to build a very simple Node.js Application.

var express = require("express");
var app = express();
var port = 3000;
 
app.get("/", (req, res) => {
  res.send("Hello World");
});
 
app.listen(port, () => {
  console.log("Server listening on port " + port);
});

What the code does is require the express.js application. It then creates app by calling express. We define our port to be 3000.

The app.use line will listen to requests from the browser and will return the text “Hello World” back to the browser.

The last line actually starts the server and tells it to listen on port 3000.

Installing Express

Our app.js required the Express.js module. We need to install express in order for this to work properly. Go to your terminal and enter this command.

npm install express --save

This command will install the express module into our package.json. The module is installed as a dependency in our package.json as shown below.

To test our application you can go to the terminal and enter the command

node app.js

Open up a browser and navigate to the url http://localhost:3000

You will see the following in your browser

Creating Website to Save Data to MongoDB Database

Instead of showing the text “Hello World” when people view your application, what we want to do is to show a place for user to save data to the database.

We are going to allow users to enter a first name and a last name that we will be saving in the database.

To do this we will need to create a basic HTML file. In your terminal enter the following command to create an index.html file.

touch index.html

In our index.html file we will be creating an input filed where users can input data that they want to have stored in the database. We will also need a button for users to click on that will add the data to the database.

Here is what our index.html file looks like.

<!DOCTYPE html>
<html>
  <head>
    <title>Intro to Node and MongoDB<title>
  <head>

  <body>
    <h1>Into to Node and MongoDB<&#47;h1>
    <form method="post" action="/addname">
      <label>Enter Your Name<&#47;label><br>
      <input type="text" name="firstName" placeholder="Enter first name..." required>
      <input type="text" name="lastName" placeholder="Enter last name..." required>
      <input type="submit" value="Add Name">
    </form>
  <body>
<html>

If you are familiar with HTML, you will not find anything unusual in our code for our index.html file. We are creating a form where users can input their first name and last name and then click an “Add Name” button.

The form will do a post call to the /addname endpoint. We will be talking about endpoints and post later in this tutorial.

Displaying our Website to Users

We were previously displaying the text “Hello World” to users when they visited our website. Now we want to display our html file that we created. To do this we will need to change the app.use line our our app.js file.

We will be using the sendFile command to show the index.html file. We will need to tell the server exactly where to find the index.html file. We can do that by using a node global call __dirname. The __dirname will provide the current directly where the command was run. We will then append the path to our index.html file.

The app.use lines will need to be changed to
app.use("/", (req, res) => {   res.sendFile(__dirname + "/index.html"); });

Once you have saved your app.js file, we can test it by going to terminal and running node app.js

Open your browser and navigate to “http://localhost:3000”. You will see the following

Connecting to the Database

Now we need to add our database to the application. We will be connecting to a MongoDB database. I am assuming that you already have MongoDB installed and running on your computer.

To connect to the MongoDB database we are going to use a module called Mongoose. We will need to install mongoose module just like we did with express. Go to your terminal and enter the following command.
npm install mongoose --save

This will install the mongoose model and add it as a dependency in our package.json.

Connecting to the Database

Now that we have the mongoose module installed, we need to connect to the database in our app.js file. MongoDB, by default, runs on port 27017. You connect to the database by telling it the location of the database and the name of the database.

In our app.js file after the line for the port and before the app.use line, enter the following two lines to get access to mongoose and to connect to the database. For the database, I am going to use “node-demo”.

var mongoose = require("mongoose"); mongoose.Promise = global.Promise; mongoose.connect("mongodb://localhost:27017/node-demo");

Creating a Database Schema

Once the user enters data in the input field and clicks the add button, we want the contents of the input field to be stored in the database. In order to know the format of the data in the database, we need to have a Schema.

For this tutorial, we will need a very simple Schema that has only two fields. I am going to call the field firstName and lastName. The data stored in both fields will be a String.

After connecting to the database in our app.js we need to define our Schema. Here are the lines you need to add to the app.js.
var nameSchema = new mongoose.Schema({   firstName: String,   lastNameName: String });

Once we have built our Schema, we need to create a model from it. I am going to call my model “DataInput”. Here is the line you will add next to create our mode.
var User = mongoose.model("User", nameSchema);

Creating RESTful API

Now that we have a connection to our database, we need to create the mechanism by which data will be added to the database. This is done through our REST API. We will need to create an endpoint that will be used to send data to our server. Once the server receives this data then it will store the data in the database.

An endpoint is a route that our server will be listening to to get data from the browser. We already have one route that we have created already in the application and that is the route that is listening at the endpoint “/” which is the homepage of our application.

HTTP Verbs in a REST API

The communication between the client(the browser) and the server is done through an HTTP verb. The most common HTTP verbs are
GET, PUT, POST, and DELETE.

The following table explains what each HTTP verb does.

HTTP Verb Operation
GET Read
POST Create
PUT Update
DELETE Delete

As you can see from these verbs, they form the basis of CRUD operations that I talked about previously.

Building a CRUD endpoint

If you remember, the form in our index.html file used a post method to call this endpoint. We will now create this endpoint.

In our previous endpoint we used a “GET” http verb to display the index.html file. We are going to do something very similar but instead of using “GET”, we are going to use “POST”. To get started this is what the framework of our endpoint will look like.

app.post("/addname", (req, res) => {
 
});
Express Middleware

To fill out the contents of our endpoint, we want to store the firstName and lastName entered by the user into the database. The values for firstName and lastName are in the body of the request that we send to the server. We want to capture that data, convert it to JSON and store it into the database.

Express.js version 4 removed all middleware. To parse the data in the body we will need to add middleware into our application to provide this functionality. We will be using the body-parser module. We need to install it, so in your terminal window enter the following command.

npm install body-parser --save

Once it is installed, we will need to require this module and configure it. The configuration will allow us to pass the data for firstName and lastName in the body to the server. It can also convert that data into JSON format. This will be handy because we can take this formatted data and save it directly into our database.

To add the body-parser middleware to our application and configure it, we can add the following lines directly after the line that sets our port.

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Saving data to database

Mongoose provides a save function that will take a JSON object and store it in the database. Our body-parser middleware, will convert the user’s input into the JSON format for us.

To save the data into the database, we need to create a new instance of our model that we created early. We will pass into this instance the user’s input. Once we have it then we just need to enter the command “save”.

Mongoose will return a promise on a save to the database. A promise is what is returned when the save to the database completes. This save will either finish successfully or it will fail. A promise provides two methods that will handle both of these scenarios.

If this save to the database was successful it will return to the .then segment of the promise. In this case we want to send text back the user to let them know the data was saved to the database.

If it fails it will return to the .catch segment of the promise. In this case, we want to send text back to the user telling them the data was not saved to the database. It is best practice to also change the statusCode that is returned from the default 200 to a 400. A 400 statusCode signifies that the operation failed.

Now putting all of this together here is what our final endpoint will look like.

app.post("/addname", (req, res) => {
  var myData = new User(req.body);
  myData.save()
    .then(item => {
      res.send("item saved to database");
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
    });
});
Testing our code

Save your code. Go to your terminal and enter the command node app.js to start our server. Open up your browser and navigate to the URL “http://localhost:3000”. You will see our index.html file displayed to you.

Make sure you have mongo running.

Enter your first name and last name in the input fields and then click the “Add Name” button. You should get back text that says the name has been saved to the database like below.

Access to Code

The final version of the code is available in my Github repo. To access the code click here. Thank you for reading !

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Node.js for Beginners

Learn Node.js from Scratch (Step by Step)

Welcome to my course "Node.js for Beginners - Learn Node.js from Scratch". This course will guide you step by step so that you will learn basics and theory of every part. This course contain hands on example so that you can understand coding in Node.js better. If you have no previous knowledge or experience in Node.js, you will like that the course begins with Node.js basics. otherwise if you have few experience in programming in Node.js, this course can help you learn some new information . This course contain hands on practical examples without neglecting theory and basics. Learn to use Node.js like a professional. This comprehensive course will allow to work on the real world as an expert!
What you’ll learn:

  • Basic Of Node
  • Modules
  • NPM In Node
  • Event
  • Email
  • Uploading File
  • Advance Of Node

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.