Reputation: 13
//I can split a string in the following way without problem
var string1 = "abc def ghi";
var res = string1.split(" ");
var split1 = res[1]; // abc
var split2 = res[2]; // def
var split3 = res[3]; // ghi
//But my string that has to be split is coming from reading a textfile (text) //Unfortunately this is not working
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
var res = text.split(" ");
var split1 = res[1];
var split2 = res[2];
var split3 = res[3];
Upvotes: 0
Views: 448
Reputation: 5581
Assuming this is Javascript and not Java code, the problem is that you're trying to access the text
variable outside of the callback function. The value from the readFile
will only be available inside of its callback function.
You should use fs.readFileSync
to get the value directly and work with it. See documentation for more details on using the function, but this should work:
var fs = require("fs")
var text = fs.readFileSync("./mytext.txt")
var textByLine = text.split("\n")
console.log("first line:",textByLine[0])
Upvotes: 2