繁体   English   中英

通过调用服务器端javaScript从Node.JS Express中的静态文件写入文件

[英]Write to file from static file in Node.JS Express by calling server side javaScript

我有一个node.js项目,可以从app.js文件写入文件。 App.js启动服务器并在我的公用文件夹中运行index.html的内容。 问题是我无法从公用文件夹中的javascript写入文件,我想这是因为其中的所有javascript都是客户端。 如何调用服务器端JavaScript,以便可以执行I / O?

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

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 (更轻松)或获取API(更多样板但具有本机功能,无需外部模块)调用此终结点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM