我有一个node.js项目,我可以从app.js文件写入一个文件。 App.js启动服务器并在我的公共文件夹中运行index.html的内容。问题是我无法从公共文件夹中的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');
});
}
我如何调用服务器端的JavaScript以便我可以进行I / O操作?
你没有。永远不能。
如果客户端和服务器端之间存在分离,则有理由这样做。安全性大多数,但也是一个关注点的分离。
虽然node.js允许您呈现视图,但它仍然是一个后端框架,后端和生成的前端不以任何方式链接。即使像Rails这样的整体框架看起来好像从后端和前端只有一个块也是分开的,它们只是有很好的抽象来隐藏两者之间的分离。
您将需要在express中创建将执行所述函数的路由。
app.get('/hello-world', function(){
// Insert your logic here
})
然后在您的前端,使用Axios(更简单)或fetch API(更多样板文件但是本机函数,不需要外部模块)来调用此端点。