|
| 1 | +/* -- exercise */ |
| 2 | +import fs from "fs"; |
| 3 | + |
| 4 | +interface Content { |
| 5 | + name: string; |
| 6 | + age: number; |
| 7 | + birthdate: string; |
| 8 | + programmingLanguages: string[]; |
| 9 | +} |
| 10 | + |
| 11 | +const content: Content = { |
| 12 | + name: "Qwik Zgheib", |
| 13 | + age: 22, |
| 14 | + birthdate: "2002-11-09", |
| 15 | + programmingLanguages: ["JavaScript", "Typescript", "Python"], |
| 16 | +}; |
| 17 | + |
| 18 | +type FileType = "json" | "xml"; |
| 19 | + |
| 20 | +const exerciseMain = { |
| 21 | + createfile: (filename: string, content: Content, type: FileType = "json"): void => { |
| 22 | + try { |
| 23 | + const jsonContent: string = JSON.stringify(content); |
| 24 | + if (type === "json") fs.writeFileSync(`${filename}.json`, jsonContent); |
| 25 | + if (type === "xml") { |
| 26 | + const xmlContent: string = `<data> |
| 27 | + <name>${content.name}</name> |
| 28 | + <age>${content.age}</age> |
| 29 | + <birthdate>${content.birthdate}</birthdate> |
| 30 | + <programmingLanguages> |
| 31 | + ${content.programmingLanguages.map((lang) => `<language>${lang}</language>`).join("")} |
| 32 | + </programmingLanguages> |
| 33 | + </data>`; |
| 34 | + fs.writeFileSync(`${filename}.xml`, xmlContent); |
| 35 | + } |
| 36 | + } catch (error) { |
| 37 | + console.error(error); |
| 38 | + } |
| 39 | + }, |
| 40 | + readFile: (filename: string): void => { |
| 41 | + try { |
| 42 | + const jsonContent: string = fs.readFileSync(`${filename}.json`, "utf-8"); |
| 43 | + const xmlContent: string = fs.readFileSync(`${filename}.xml`, "utf-8"); |
| 44 | + console.log(`Reading ${filename}.json\n`, jsonContent); |
| 45 | + console.log(`\nReading ${filename}.xml\n`, xmlContent); |
| 46 | + } catch (error) { |
| 47 | + console.error(error); |
| 48 | + } |
| 49 | + }, |
| 50 | + deleteFile: (filename: string): void => { |
| 51 | + try { |
| 52 | + console.log("Deleting files..."); |
| 53 | + fs.unlinkSync(`${filename}.json`); |
| 54 | + fs.unlinkSync(`${filename}.xml`); |
| 55 | + } catch (error) { |
| 56 | + console.error(error); |
| 57 | + } |
| 58 | + }, |
| 59 | +}; |
| 60 | + |
| 61 | +exerciseMain.createfile("data", content, "json"); |
| 62 | +exerciseMain.createfile("data", content, "xml"); |
| 63 | + |
| 64 | +exerciseMain.readFile("data"); |
| 65 | +exerciseMain.deleteFile("data"); |
0 commit comments