Files
30-seconds-of-code/snippets/read-file-to-array.md
Stefan Feješ b848906fe5 fix naming
2017-12-17 15:41:31 +01:00

588 B

Read file as array of lines

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 spliting file content line by line(each \n).

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']
*/