我正在努力解决一件我似乎在任何地方都找不到答案的事情。我正在收集数据,并将数据吐入一个包含对象数组的json文件(intake.json)中。我正在尝试编写一个函数,当调用该函数时,它将获取intake.json文件并写入.txt文件,然后格式化该文件。
当我
console.log
这个
element
在for循环中是吐出每个单独的字符。。。
前-
D
a
t
e
:
0
6
/
1
2
/
2
4
如有任何帮助,我们将不胜感激:
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", "utf8", function(err, json) {
if (err) {
console.log(err);
}
const writtenData = []
for (let index = 0; index < json.length; index++) {
const element = json[index];
console.log('element', element);
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}\n\n
`)
}
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');