#Cannot add to array within method
30 messages · Page 1 of 1 (latest)
array is [] (empty)
if i do ```js
r.on("line", function (text) {
console.log(text)
})
console.log(array) in the function?
that works
what is the output?
its ['line1', 'line'2, 'line3']
ummmm thats kinda weird
is there another way to read a txt file and each line is a sperate element of an array?
just do fs.readFile and use .split('\n')
whats a better ide for js, vscode or intellij?
like ```js
const fs = require('fs');
let line = fs.readLine("finishedWordList.txt")
let splittedLines = line.split("\n")
console.log(splittedLines)
the as is pretty unexpected, also readLine is readFile, also it is async, so you need to put the other stuff in a callback
or you could use readFileSync if you want it sync
is there a way in vscode to show the functions for fs
no, but you dont rly need to just search it up
fs.readFile('theFile.txt','utf-8',function(err,data) {
if (err) throw err;
console.log(data.split('\n'))
})
this still returns an empty list outside the function, inside it it works
ye everything that runs after the file is read must be put inside the callback
is there any way to use it outside of the callback
you cant
and now i figured that the original problem is that you didnt put the stuff inside of the callback
you can use readFileSync tho, but you gotta search it up for that one
found an example
const fs = require('fs');
try {
const data = fs.readFileSync('/Users/joe/test.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
just cause im tryna transfer my code from c# to js for a website and yh
why is it pushed like wrote\n to the array? i know \n means new line but if its reading every line it shouldnt need to have that as well
but it is reading the file not the line lol