Legend
Legend

Reputation: 116840

What does it mean to share code between server and client in Javascript?

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?

Upvotes: 8

Views: 518

Answers (3)

Anurag
Anurag

Reputation: 141879

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>

Upvotes: 2

Jeremy Whitlock
Jeremy Whitlock

Reputation: 3818

That is correct. If your server and client use the same programming language, in this case JavaScript, you could write one implementation of a function/class/etc. and use that on both the client and the server. This is different than most other scenarios where you have Python/Java/etc. on the server and JavaScript on the client.

Upvotes: 0

David Tang
David Tang

Reputation: 93674

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.

Upvotes: 5

Related Questions