forked from Chalarangelo/30-seconds-of-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7d874b0
commit bd3ed71
Showing
2 changed files
with
20 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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'] | ||
*/ | ||
``` |
This file contains 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