我想在Node Js中已经创建的文件中写入文本。这就是我所做的
Upload.html
<form enctype ="multipart/form-data" action ="/file" method ="post">
MAC Address:<br>
<input type="text" name="macadd" id="macadd"><br>
Percentage:<br>
<input type="text" name="percent" id="percent"><br>
<input type="submit" value='Submit' id="upload">
<br>
</form>
App.js
app.route('/file').post(function (req,res,next) {
var macadd =req.body.macadd;
//var percent =req.body.percent;
var path ="C:\Proj\doc\data.txt";
var data ="hello";
fs.writeFile(path,macadd , function(error) {
if (error) {
console.error("write error: " + error.message);
} else {
console.log("Successful Write to " + path);
}
});
});
我想将'macadd'的值写入data.txt文件中。它主要是一个整数值,但当我点击提交时,在文件中它显示为“未定义”,即使它在控制台上显示为成功写入。任何解决方案?
答案 0 :(得分:1)
您需要更改指定路径的方式:
var path ="C:\Proj\doc\data.txt";
应该是:
var path ="C:/Proj/doc/data.txt";
答案 1 :(得分:1)
您可以使用path-resolve
之类的节点实用程序来帮助您:
路径解析:https://www.npmjs.com/package/path-resolve
$ npm install path-resolve --save
然后使用如下:
var resolve = require('path-resolve');
var path = resolve("C:\Proj\doc\data.txt").replace(/\\/g,'/');
答案 2 :(得分:1)
我刚刚在路径的文件夹之间添加了2个斜杠,并添加了path-resolve包。像这样:
var path =resolve("C:\\Proj\\doc\\data.txt");
为了将文本框的值添加到文件中,我必须删除表单标记中的加密类型。
<form action ="/file" method ="post">
MAC Address:<br>
<input type="text" name="macadd" id="macadd"><br>
Percentage:<br>
<input type="text" name="percent" id="percent"><br>
<input type="submit" value='Submit' id="upload">
<br>
</form>