Last active
January 6, 2021 15:22
-
-
Save dev-opus/f0ac82b0c9df01cd1db656c7f7962a43 to your computer and use it in GitHub Desktop.
file system and streams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs').promises | |
const path = require('path') | |
const getData = async (dirName) => { | |
try { | |
const buffer = await fs.readFile(dirName) | |
const data = await JSON.parse(buffer) | |
return data | |
} catch (err) { | |
console.error(err) | |
} | |
} | |
const writeDataToFile = async (dirName) => { | |
try { | |
const data = await getData('data.json') | |
const outputDir = path.join(__dirname, 'output') | |
await fs.mkdir(outputDir) | |
await fs.writeFile( | |
path.resolve(outputDir, 'output.txt'), | |
`name of product: ${data.name}\nprice: $${data.details.price}\n`, | |
{ flag: 'a' } | |
) | |
console.log('program finished! check the output directory') | |
} catch (err) { | |
console.error(err) | |
} | |
} | |
const main = async () => { | |
const dir = path.resolve(__dirname, 'output') | |
writeDataToFile(dir) | |
} | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
a dummy program to demonstrate | |
my knowledge of streams in | |
node.js | |
*/ | |
const fs = require('fs') | |
const path = require('path') | |
// READABLE STREAMS | |
let data = '' | |
const readable = fs.createReadStream(path.resolve(__dirname, 'dummy.txt'), { | |
encoding: 'utf-8', | |
}) | |
readable.on('data', (chunk) => { | |
return (data += chunk) | |
}) | |
readable.on('error', (err) => { | |
console.error(err.stack) | |
}) | |
readable.on('end', () => { | |
console.log('data from "flowing" readstream:', data) | |
}) | |
// WRITEABLE STREAMS | |
const readable2 = fs.createReadStream(path.resolve(__dirname, 'dummy2.txt')) | |
const writeable = fs.createWriteStream(path.resolve(__dirname, 'dummy3.txt')) | |
readable2.addListener('data', (chunk) => { | |
writeable.write(chunk) | |
}) | |
readable2.addListener('end', () => { | |
console.log('data from dummy2.txt is now in dummy3.txt') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment