How to read local text file into a JS

How to read local text file into a JS
0

#1

Hi, I need help for JS code. I could not read dancers.txt with belowing code. Please don’t say to me about use read(). I tried to in below code block. Also, I have a another problem. In sublime text, .split("\n") is wrong for editor. I did not initialize it. What can I do? Thanks for yours helping comment.

// For reading .txt file code block
var fs = require("fs");
var text = fs.readFileSync("./dancers.txt");
var textByLine = text.split("\n")
// General Code
function getDancers(males, females) {
var names = read("dancers.txt").split("\n"); 
for (var i = 0; i < names.length; ++i) {
          names[i] = names[i].trim();
       }
for (var i = 0; i < names.length; ++i) { 
var dancer = names[i].split(" "); 
var sex = dancer[0];
var name = dancer[1];
if (sex == "F") {
females.enqueue(new Dancer(name, sex));
} else {
males.enqueue(new Dancer(name, sex)); }
} }

#2

If you are running the code on a browser console, you will not be able to access local files on your computer, this is built into the browsers for security reasons. To solve this use node.js on your local machine, this allows you to run javascript files from the terminal. If you are already using node on the local machine, try adding toString() before calling the split() function.

var fs = require('fs');
var textByLine = fs.readFileSync('dancers.txt').toString().split("\n");

As for the editor problem, you can write your code in sublime text and then paste it into gedit or nano before running it, see if the problem still arises.
Hope this helps.