尝试将请求简单地PUT到Node.js中的JSON文件
Trying to simple PUT request to JSON file in Node.js
我试图创建一个PUT方法来更新obj.json文件,并在上传后显示其内容。我得到一个空的物体,没有内容?
function upload(response, request) {
console.log("Request handler 'upload' was called.");
var form = new formidable.IncomingForm();
console.log("about to parse");
form.parse(request, function(error, fields, files){
response.writeHead(200, {'content-type': 'application/json'});
response.write('received upload:'n'n');
response.end(util.inspect({fields: fields, files: files}));
});
form.on('file', function(field, file) {
console.log(file);
if (file.type == 'application/json') {
jsonObject = JSON.parse(fs.readFileSync(file.path, 'utf8'));
console.log(jsonObject);
} else { console.log('wrong file');}
});
}
function update(response, request) {
console.log("Request handler 'update' was called.");
response.writeHead(200, {"Content-Type": "application/json"});
var form = new formidable.IncomingForm();
console.log("about to parse");
form.parse(request, function(error, fields, files){
response.writeHead(200, {'content-type': 'application/json'});
response.write('ready to update:'n'n');
response.end(util.inspect({fields: fields, files: files}));
});
form.on('file', function(field, file) {
console.log(file);
if (file.type == 'application/json') {
JSON.parse(fs.writeFileSync(file.path, JSON.stringify('"test":"Okay"'), 'utf8'));
console.log(jsonObject);
} else { console.log('wrong file');}
});
}
我可以上传文件并访问json,但现在无法更改文件的内容。有什么想法吗?另外,删除方法会是一样的吗?
您在这里问了两个问题,因此我给您两个单独的答案。更新JSON文件就像其他任何东西一样:
var fs = require('fs');
var filename = '/tmp/content.json';
var file = fs.readFileSync(filename);
var json = JSON.parse(file);
//update the object
json.newValue = 'testValue';
//update the file with new object
fs.writeFileSync(filename, JSON.stringify(json));
https://www.npmjs.com/package/multer
这是一个很好的文件上传功能库。执行文件POST时,必须提交内容类型为"multipart/form-data"的文件。然后您可以访问JSON文件,如下所示:
req.files.<nameOfFileInput>
我从来没有使用过强大的,但我认为它的工作方式是一样的,甚至可能在幕后使用multer。我猜你的表单没有enctype="multipart/form data"集,这就是为什么你的文件没有被发送到服务器的原因。
相关文章:
- 在索引.html和应用.js [node.js] 之间共享变量
- JS(node.js)而循环不起作用
- 如何使用 JS (Node.js) 防止 HTTP 查询中允许使用 UTF8 字符串
- Angular JS & Node Webkit Routing
- 当作为脚本运行时.js Node中“this”的上下文是什么
- JS/Node:- 使用 node.io 选择标记
- JavaScript 如何让节点在返回 node.js/Node-RED 之前等待
- 处理快速连续的函数调用 - Javascript / underscore.js / node.js
- 如何在一台服务器中运行不同的.js文件.js NODE JS中的文件
- JS node-mysql bools 表现得很奇怪
- Node.js+Node Webkit+基于Node串行端口的应用程序-这可能吗
- 如何在Express.js/Node.js中检查查询字符串是否有值
- Express.Js, Node.Js, MongoDB Questions
- 在JS/Node中,当多个人编辑相同的记录时,如何避免数据冲突?有图案吗
- 服务器端js(node.js)上的同步
- 将参数从jade发送到js/node
- angular.js+node.js/electron中的Promise;不起作用
- 是否有可能确定我的应用程序的aws实例使用js/node aws-sdk
- Image Magick模块抛出奇怪的错误(Express js Node js)
- 用JS (Node.js)读取文本文件'