[英]Write to file from static file in Node.JS Express by calling server side javaScript
I have a node.js project and i can write to a file from the app.js file. 我有一个node.js项目,可以从app.js文件写入文件。 App.js starts the server and runs the content of index.html in my public folder.
App.js启动服务器并在我的公用文件夹中运行index.html的内容。 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.
问题是我无法从公用文件夹中的javascript写入文件,我想这是因为其中的所有javascript都是客户端。 How do i call server side javascript so that i can do I/O?
如何调用服务器端JavaScript,以便可以执行I / O?
Index.html - located in Public folder Index.html-位于公用文件夹中
<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 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');
});
}
How do i call server side javascript so that i can do I/O?
如何调用服务器端JavaScript,以便可以执行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. 尽管node.js允许您呈现视图,但它仍然是一个后端框架,并且后端和生成的前端没有任何链接。 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.
即使像Rails这样的整体框架似乎都离后端和前端只有一个街区是分开的,它们也有很好的抽象来隐藏两者之间的分隔。
You'll want to create a route in express that will execute said function. 您将要创建一个Express路线来执行上述功能。
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). 然后在您的前端上,使用Axios (更轻松)或获取API(更多样板但具有本机功能,无需外部模块)调用此终结点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.