I try using Nodejs to write string and json data to output.json file but it is not working. To be more specific, i want to first write a string to a file C. Next, read some data from file B and use the data to write to file C again. I test the code separately, the separate part of writing string and writing json works perfectly but it is not working if i use them together.
Expected output:
this is some string
json data
However, my output is:
json data
Here is my code:
// write strings to file
var fs = require('fs');
fs.writeFile('/data/outputjson', 'this is some string', function(err) {
if(err) {
return console.log(err);
}
console.log("The file was written successfully!");
});
// read file
var jsonfile = require('jsonfile');
var file = 'data/routes.json';
var routes;
var links=[];
jsonfile.readFile(file, function(err, obj) {
routes=obj;
for(var i=0;i<routes.length;i++){
links.push({
source: routes[i]["geocoded_waypoints"][0]["place_id"],
target: routes[i]["geocoded_waypoints"][1]["place_id"]
});
}
console.log(links);
// write json to file
var jsonfile = require('jsonfile')
var file = 'data/output.json'
jsonfile.writeFileSync(file, links)
})
via SHE
No comments:
Post a Comment