Im trying to solve something i cant seem to find the answer to anywhere. Im collecting data and the spitting the data into a json file (intake.json) which contains an array of objects. Im trying to write a function that, when called, will take the intake.json file and write to a .txt file and then format the file. I cant seem to get things right. Any help would be appreciated:
index.js
#!/usr/bin/env node
const style = require('node:util');
const yargs = require("yargs");
const prompt = require('prompt-sync')({sigint: true});
const fs = require('node:fs');
console.clear();
const intakeType = prompt(style.styleText('green','Please Enter the intake type:'));
const date = prompt(style.styleText('green','Please enter the intake date (mm/dd/yy): '));
const project = prompt(style.styleText('green','Please Enter the Project: '));
const reporter = prompt(style.styleText('green','Please enter the reporter: '));
const team = prompt(style.styleText('green','Please enter the team of the report: '));
const time = prompt(style.styleText('green','Please enter the time taken: '));
const details = prompt(style.styleText('green','Please enter the details of the intake: '));
const resolution = prompt(style.styleText('green','Please enter the resolution type: '));
const content = {
intakeType,
date,
project,
reporter,
team,
time,
details,
resolution
}
const JSONToFile = (obj) => {
fs.readFile("intake.json", { flag: 'r' }, function(err, json) {
var array = JSON.parse(json);
array.push(obj);
if(err){
console.log(err);
return;
}
fs.writeFile("intake.json", JSON.stringify(array, null, 2), { flag: 'w' }, function(err) {
if (err) {
console.log(err);
return;
}
console.log("The intake was saved!");
});
});
}
JSONToFile(content);
// function to convert the json file to a .txt file
const convertToTxt = () => {
fs.readFile("intake.json", { flag: 'r' }, function(err, json) {
if (err) {
console.log(err);
}
const writtenData = []
for (let index = 0; index < json.length; index++) {
const element = json[index];
writtenData.push( `
Date: ${element.date} n
Reporter: ${element.reporter} n
Time Taken: ${element.time} n
Team: ${element.team} n
Project: ${element.project} n
Intake Type: ${element.intakeType} n
Details: ${element.details} n
Resolution: ${element.resolution}nn
`)
}
fs.writeFile("intake.txt", JSON.stringify(writtenData, null, 2), function(err) {
if (err) {
console.log(err);
} else {
console.log(style.styleText('green','Text file successfully created'))
}
});
});
}
convertToTxt('intake.json');