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