diff --git a/snippets/read-file-to-array.md b/snippets/read-file-to-array.md new file mode 100644 index 000000000..451e2dd06 --- /dev/null +++ b/snippets/read-file-to-array.md @@ -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'] + */ +``` \ No newline at end of file diff --git a/tag_database b/tag_database index 3acb709f1..8f05fb386 100644 --- a/tag_database +++ b/tag_database @@ -67,6 +67,7 @@ powerset:math promisify:function random-integer-in-range:utility random-number-in-range:utility +read-file-to-array:node redirect-to-URL:browser reverse-a-string:string RGB-to-hexadecimal:utility