我有一个 node.js 项目,我可以从 app.js 文件写入文件。 App.js 启动服务器并运行我的公共(public)文件夹中的index.html 的内容。问题是我无法从公共(public)文件夹中的 javascript 写入文件,我猜这是因为其中的所有 javascript 都是客户端。我如何调用服务器端 javascript 以便我可以执行 I/O?
Index.html - 位于公共(public)文件夹
<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');
});
}
最佳答案
How do i call server side javascript so that i can do I/O?
你不知道。从来没有,从来没有。
如果客户端和服务器端之间存在分离,那么这是有原因的。主要是安全性,但也有关注点分离。
虽然node.js允许渲染 View ,但它仍然是一个后端框架,后端和生成的前端没有以任何方式链接。 即使是像 Rails 这样的整体框架,看起来好像后端和前端只有一个 block 是分开的,它们只是有很好的抽象来隐藏两者之间的分离。
您需要在express中创建一条执行上述函数的路由。
app.get('/hello-world', function(){
// Insert your logic here
})
然后在您的前端,使用 Axios 调用此端点(更简单)或 fetch API(更多样板,但 native 函数,不需要外部模块)。
关于javascript - 通过调用服务器端 javaScript 从 Node.JS Express 中的静态文件写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51161859/