Hi everyone,
I have made some basic functions in Node.js that read and write to other files. I need to call these functions on command, such as when a button is pressed. Here is one example of the logic that I need:
<button onClick="readFileWithNodeJS()">Click me</button>
I have a file called test.js with two functions: readFile() and writeFile(param) and then a handler method. I need to call these functions from my client-side javascript.
test.js:
var fs = require(“fs”);
function readFile() {
fs.readFile("src/textFiles/testFile.txt", function(err, buf) {
if (buf) {
console.log(buf.toString());
return buf.toString();
}
});
}
function writeFile(data) {
fs.writeFile("src/textFiles/testFile.txt", data, function(err) {
if (err) {
console.log(err);
} else {
console.log("Success");
}
});
}
exports.handler = function(event, context, callback) {
callback(null, { statusCode: 200, body: "Hi" });
}
I have done extensive research over the past week and I’m seeing that I need to make an HTTP request. For me, since I am testing it locally on port 8888, the endpoint url for the functions would be http://localhost:8888/.netlify/functions/test. I am using $.post and sending a request to that url. This is the request I am making:
$.post(“/.netlify/functions/test”, {},
function(data, status) {
console.log(data);
}, “text”);
I have a few questions about how this all works:
-
If I have a specific function that I want to use in node.js, does each function have to be in its own file with its own handler method? For example, I have the readFile() function I mentioned earlier. To use that method specifically, would I need to create another file called read.js and create another handler function that would complete the functionality, and then request would be directed to http://localhost:8888/.netlify/functions/read, or is there a way to do this in one file?
-
If I want to actually send some data with the POST request, how would I access that at the endpoint in test.js? For example, if I am trying to use the writeFile(data) function and I pass {newData: “This should be the new contents of testFile.txt”} as the data in the post request, how would I access that as plain text so that I could just use fs.writeFile as shown in the function above.
I am just diving into this complex world for the first time and would greatly appreciate some assistance. I appreciate anyone who would be willing to help out.
Thanks.