0

I just started learning node js and I am stuck with the following (I spent hours looking into stackoverflow but didn't get what I want): I am trying to export some data from node js to a js file.

I have 3 files :

  1. script.js
  2. app.js
  3. data.json

In app.js I coded :

const path = require('path');
const fs = require('fs');
const data = path.join(__dirname, '../data/data.json');

const data = fs.readFileSync(`${data}`, "utf-8");

So till now, all's good. I can get and display the data on the vs terminal. Now I want to export this data and to get it from the script.js file that will feed html with the exported data. So on app.js I added :

module.exports = data;

On script.js, to get data, I coded :

import data from '../src/app.js'
console.log(data)

Then on the browser console I got this error : GET http://localhost:5000/src/app net::ERR_ABORTED 404 (Not Found)

Why do I have this GET method error, as I'm just trying to get some data from app.js to script.js ? Is there a way to get it ?

Thanks for your help !

  • Have you tried using require in script.js instead of import? – Vincent M Aug 31 '21 at 22:43
  • You should use `const file = path.join(__dirname, '../data/data.json');` and `const data = fs.readFileSync(file, "utf-8");`. As for reading server-side data in your browser JS code, it unfortunately is a bit more complicated than that. Just because you're using JS both on the server (node) and inside the browser doesn't mean they talk directly to each other. You need to provide a route to request the data from the server. –  Aug 31 '21 at 22:43
  • With express you would do: `app.use('/data', (req, res) => res.json(data));` then in your browser you would do `fetch('/data').then(r => r.json()).then(data => { /* do something with data */});` –  Aug 31 '21 at 22:46
  • 1
    Useful reading: [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) –  Aug 31 '21 at 22:48
  • In practice you either `export default data` and `import data from yourfile` (ES6 style) or `module.exports = data` and `const data = require(yourfile)` (NodeJS style) – savageGoat Aug 31 '21 at 22:57
  • @VincentM I tried require and on the browser console I got the error : require is undefined – maheddar Aug 31 '21 at 23:37
  • @ChrisG thanks for the insights, so I have to set a route to get the data from the server. I will try that with express, and thanks again ! – maheddar Aug 31 '21 at 23:48

0 Answers0