我有一个JSON对象如下
{" A":1," B":2," C":3}
如何使用节点js
将JSON写入具有以下格式的属性文件中A=1
B=2
C=3
我试过这种方式
我试过这个
app.post('/writeprop', function (req, res) {
logger.log('info', 'Write Properties : ' + "args" + req.body.propObj);
fileHandler.writeProperties( req.body.propObj, function (error, values){
logger.log('info', "Writing Properties.. ");
if (error == null) {
res.send(values);
}
else {
logger.log('info', error);
}
});
});
function writeProperties(pptObj, callback){
properties.stringify (pptObj, { path: basePath + 'test.properties' }, function (error, obj){
if (error){
callback(error, null);
return console.error (error);
} else {
console.log (obj);
callback(null, obj);
return;
}
});
}
它无法正常工作。
答案 0 :(得分:0)
这是一个工作示例代码:
var fs = require('fs');
var path = require('path');
var file = "./sample.txt";
var json = '{ "A":1, "B":2, "C":3 }';
fs.open(file, 'a', function(err, fd) {
if (err) {
try {
throw new Error("Something wrong happend");
} catch(e) {
console.log("Error writing into file" + e);
}
}
var jsonParsed = JSON.parse(json);
for (var el in jsonParsed) {
var buffer = new Buffer(el + " = " + jsonParsed[el] + '\n');
var bufferLength = buffer.length;
var bufferPosition = 0;
var filePosition = null;
fs.write(fd, buffer, bufferPosition, bufferLength, filePosition,
function(err, written) {
if(err) {
throw new Error(err);
}
console.log('Wrote ' + written + ' bytes');
});
}
});
请注意,您需要一个有效的json对象,这意味着您需要将json对象放在引号之间。
答案 1 :(得分:0)
当我将pptObj作为obj而不是字符串传递时,它起作用了。
<a href="#" id="test">Click me</a>
<br/>
<br/>
<table>
<tr>
<td>Some text..</td>
<td>Some more text..</td>
<td>Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text
Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text
Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text
Lots of text Lots of text Lots of text Lots of text Lots of text Lots of text
</td>
</tr>
</table>
解决问题。谢谢。