1

I'm running a test app in Express.js using EJS as the templating engine. I'd like to access functions stored in a .js file to run server side and not client side. For instance if I have:

<%= console.log("I'm in the server console"); %>

the server catches the console output, and if I have:

<script type="text/javascript"> console.log("I'm in the client-side console"); </script>

Now if I have a function to output the same for the client side I can include it this way:

<script type="text/javascript" src="/javascripts/clientSideCode.js"> clientSideOutput(); </script>

But how do I include a file and its functions that way so EJS can execute server side code? It appears that the public folder in express is just for client side code.

1
  • Look at helper functions. Commented Feb 2, 2013 at 22:20

3 Answers 3

2

You can create helper functions that your templates can access via app.locals:

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure that's exactly what I'm looking for. Does that just expose an object or a whole function. Let's day I have a function named createFile that would create a file on the server after someone clicks on a link, how would I do that?
It sounds like you're looking for a route. To create a file on the server when someone clicks a link, you'll want to use ajax (or a POST to a renderable page) and a route on the server that can create files.
0

You can use node.js and Socket.IO to emit real time events between client and server. For instance the client would do something like:

<script>window onload = function() {

socket.emit('request_customer_list', { state: "tx" });

socket.on('receive_customer_list', function(data) {
$.each(data.customer_list, function(key, value) {

  socket.set(key, value); // store the customer data and then print it later
});

});}

On your server you can have a routine to load the customer list and send it back in similar format:

socket.on('connection')
  socket.on('request_customer_list', function(data){
   state = data.state;
   var customer_list;
   // pretend i loaded a list of customers from whatever source right here
   socket.emit('receive_customer_list', {customer_list: customer_list});
)} )};

Comments

0

The helper function is definitely the way to go, as @hunterloftis said, and then access it via EJS. To expand on his answer:

app.js:

clientSideOutput() {
    // Your code
}

const app = express()

app.set('view engine', 'ejs')
app.locals.clientSideOutput= clientSideOutput

Yout template.ejs file:

<div>
    Some text, then <%= clientSideOutput() %>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.