简体   繁体   中英

How to send data from server to client in node?

I want to send a data to the client side to build a library with Twig. In server side ( server.js ) I have an array ( ['item1', 'item2'] ) and I want to retrieve this data from the clients side in a file ( library.js ) to manipulate the DOM of my view ( library.twig ). How can I do ? With a call api or with json. Thank you a lot.

server.js

const mp3File = fs.readdirSync(join(__dirname, './upload')).filter(file => file.endsWith('.mp3'));
console.log(mp3File);

library.js

// retrieve the data here
// console.log(mp3File);

library.twig

{% block content %}
    <div class="content">
       {# manipulate the dom with the data here #}
    </div>
{% endblock %}

{% block javascripts %}
    <script src="../../dist/library.js"></script>
{% endblock %}

Well this is rather large question and teaching this subject from the ground level to top is not purpose of stackoverflow. Instead let me guide you towards the right direction and materials.

Usually in Node.js frameworks are used to lessen bloatcode required for servers. One of such (popular) frameworks is express and they have comprehensive getting started guides.

Steps you need to take:

  1. Setup server to listen for calls from client
  2. Create routing for server (this is the API)
  3. Serve file through a route
  4. Request the file from client

More examples can be found all over the internet, for example here and here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM