0
votes

I am a PHP developer and have recently made some use of node JS with express.

One thing i am confused about is how you tell your express server if a javascript file should be executed on the server or sent to the browser to be executed on the client side.

In PHP this is not a problem because each filetype (php, pearl, jpg, js) has a dedicated location (server or client) where it runs. The same is true of HTTP apps programmed other languages such as Java and C#

consider this sample code

var express = require('express'); var app = express();

app.get('/some_page', function(req, res) { res.send('hello world'); });

app.listen(3000);

There is no JS involved so 'hello world' is sent to the browser and is rendered by the browser.

But what if the code was

var express = require('express'); var app = express();

app.get('/', function(req, res){ res.send('console.log('hello world')'); });

app.listen(3000);

This time we have the JS function console.log() So how does node.js know if if should run this code or send it to the browser.

3
It seems you need to learn basics of node.js prior jumping to express.jsZeeshan Hassan Memon

3 Answers

4
votes

this is all whithin the app.get('/', function(req, res){ and } tags

res.send('console.log("hello world!")')

will print console.log("hello world!") on the clients page

res.send('<html><body><script>console.log("hello world!");</script></body></html>')

will print hello world! in the console of the client

 res.send('hello world!');
 console.log("hello world!");

will print hello world! on the page of the client and on the servers console.

so basicly all you send to the client will be done client-side and code that you dont send to the client will be done server-side

EDIT

like Ankur Rana said you can also send Html files

res.sendFile('index.html');

and in the same directory as this file we have a file named index.html:

<html>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <div id="myId">console.log("hello world!")</div>
    <script>
        //regular js here
     $("#myId").html("Hello World!");
    </script>
</body>
</html>
0
votes

You are using express, so you should explicitly specify client side Javascript code using static middleware.

In the example below you define public directory to store it.

// GET /style.css etc
app.use(express.static(__dirname + '/public'));

Everything else will be executed on the server side.

More about middleware: http://expressjs.com/en/guide/using-middleware.html

0
votes

Put the javascript code in script tag of a HTML file and send it using res.sendFile('pathToFile.html')