I will be honest in saying that I did not quite understand one concept while digging into NodeJS. And this concept is about how NodeJS lets us share code between the server and client. What does this really mean? Does it mean that I can write a function that I perhaps call on the client side and it gets invoked as a remote method or does it mean that the code gets copied onto the client side and gets executed?
Can someone give me some intuitive example that I can wrap my head around with?
It simply means that the code that is used on the server side can also be included as <script>
s in the HTML, where applicable. The real challenge is finding opportunities where it is applicable.
One example is an input validation engine. We all know that only validation performed on the server is reliable, but client-side validation is still desirable for user experience. If a validation engine is designed in a generic enough fashion, the same code can be used on both client and server sides, avoiding a lot of duplicate effort.
Other examples include HTML templating libraries, data models, and various utility libraries such as underscore.js.
It means code is copied on the client-side and executed locally in the browser.
To give an example, say you have a js file representing a Person on your server at the path /app/model/person.js
. The contents of the file are:
function Person(id, firstName, lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
In Node.JS, you may use this Person object in some file as:
// someFile.js
include("/app/model/person");
function onLoad() {
var john = new Person(1, "John", "Malkovich");
};
The same code can be used on the client side by loading it from the same source:
<script src="/app/model/person.js"></script>
<script>
var john = new Person(1, "John", "Malkovich");
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With