0

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.

4

2 回答 2

0

您可以创建模板可以通过以下方式访问的辅助函数app.locals

于 2013-02-02T22:29:09.817 回答
0

您可以使用node.jsSocket.IO在客户端和服务器之间发出实时事件。例如,客户端会执行以下操作:

<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
});

});}

在您的服务器上,您可以有一个例程来加载客户列表并以类似的格式发回:

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});
)} )};
于 2013-07-03T22:51:41.003 回答