-1

I have a Node.js Express project with the files oriented like this (WebStorm IDE):

enter image description here

I would like to pass a variable from the marked index.js to app.js so that I can write that variable in data.json at the end.

I am still new to Node.js and still confused about the client/server theory. It will be much easier if there is a way to write the data directly from index.js to data.json, or any other json file, but I think that this is not possible according to previous answers. Please correct me if I'm wrong.


Update:

Issue was solved using Ajax as mentioned in this answer :

using $.post('/email', { address: 'xxx@example.com' }); in index.js to send data, and

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/email', (req, res) => {
  // you have address available in req.body:
  console.log(req.body.address);
  // always send a response:
  res.json({ ok: true });
});

app.use(express.static(dir));

app.listen(4443, () => console.log('Listening on http://localhost:4443/'));

in app.js to recieve data.

Heba
  • 37
  • 5
  • ` I think that this is not possible according to previous answers. ` It surely is possible. Just use `fs.writeFile`. – Jonas Wilms May 23 '18 at 15:08
  • It is very difficult to understand what you are trying to do without your posting some code. – Robert Moskal May 23 '18 at 15:15
  • @JonasW. when I tried `require('fs')` in index.js I got _require is not defined_ message, and when I looked it up, it was mentioned that we cannot use require for client side code, which I'm assuming is the index.js part. – Heba May 23 '18 at 15:38
  • Then you have to use Ajax to pass the data from the client to the backend – Jonas Wilms May 23 '18 at 15:41
  • @JonasW. I'll try that, thanks ! – Heba May 23 '18 at 16:13

1 Answers1

1

Your index.js should have a function thats returns the variable value, like this:

# index.js
exports.default = () => {
  return 'my data';
}

# app.js
const dataGetter = require('./public/javascripts/index.js');
const myData = dataGetter();

Or, if your data is static, you can just require() the index.js every time you want.

In node.js, you should declare variables in functions, functions are the nature of Node.js ecosystem.

Pedro Fernandes
  • 366
  • 3
  • 11