adding read file to array function
This commit is contained in:
19
snippets/read-file-to-array.md
Normal file
19
snippets/read-file-to-array.md
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
### Read a file to an Array
|
||||||
|
|
||||||
|
Use `readFileSync` function in `fs` node package to create a `Buffer` from a file.
|
||||||
|
convert buffer to string using `toString(encoding)` function.
|
||||||
|
creating an array from contents of file by `split`ing file content line by line(each `\n`).
|
||||||
|
|
||||||
|
```js
|
||||||
|
const fs = require('fs');
|
||||||
|
const readFileToArray = filename => fs.readFileSync(filename).toString('UTF8').split('\n');
|
||||||
|
/*
|
||||||
|
contents of test.txt :
|
||||||
|
line1
|
||||||
|
line2
|
||||||
|
line3
|
||||||
|
___________________________
|
||||||
|
let arr = readFileToArray('test.txt')
|
||||||
|
console.log(arr) // -> ['line1', 'line2', 'line3']
|
||||||
|
*/
|
||||||
|
```
|
||||||
@ -67,6 +67,7 @@ powerset:math
|
|||||||
promisify:function
|
promisify:function
|
||||||
random-integer-in-range:utility
|
random-integer-in-range:utility
|
||||||
random-number-in-range:utility
|
random-number-in-range:utility
|
||||||
|
read-file-to-array:node
|
||||||
redirect-to-URL:browser
|
redirect-to-URL:browser
|
||||||
reverse-a-string:string
|
reverse-a-string:string
|
||||||
RGB-to-hexadecimal:utility
|
RGB-to-hexadecimal:utility
|
||||||
|
|||||||
Reference in New Issue
Block a user