0

I have a node.js project and i can write to a file from the app.js file. App.js starts the server and runs the content of index.html in my public folder. The problem is that i can't write to a file from the javascript in the public folder, and i guess this is because all the javascript in there is client side. How do i call server side javascript so that i can do I/O?

Index.html - located in Public folder

 <html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
  <title>test1</title>
</head>
<body>
    <button onclick="WriteToFile()">writie to file</button> <br>
    </body>
</html>

App.js

var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();

// set static path
app.use(express.static(path.join(__dirname, 'public')));

app.listen(3000, function(){
    console.log('Server started on Port 3000...');
})

//How do i call this function or write to a file from index.html.
function WriteToFile(){
    fs = require('fs');
    fs.writeFile('helloworld.txt', 'The Function was called', function (err) {
    if (err) 
    return console.log(err);
    console.log('Wrote Hello World in file helloworld.txt, just check it');
});
}
1
  • Read about Ajax calls from the browser to your server. It's a way of making a request to your server from your client-side Javascript. You then implement a route on your server that receives the Ajax call and executes the desired code on the server. Commented Jul 3, 2018 at 21:04

1 Answer 1

1

How do i call server side javascript so that i can do I/O?

You don't. Never, ever.

If there is a separation between client and server side, there is a reason to it. Security mostly, but also a separation of concerns.

While node.js allows you to render views, it is still a back-end framework, and the back-end and generated front-end are not linked in any way. Even monolithic framework like Rails that make it seem as if there was just one block from both back-end and front-end are separate, they just have very good abstractions to hide the separation between the two.

You'll want to create a route in express that will execute said function.

app.get('/hello-world', function(){
// Insert your logic here
})

Then on your front-end, call this endpoint using either Axios (easier) or the fetch API (more boilerplate but native function, no need for an external module).

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

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.