Reputation: 39
I'm trying to read a local text file (not over web). So, that I can parse it into a array. But I get the error: "file.open is not a function"
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var util = require('util');
var clients = [];
const fs = require('fs');
......................
/// read from file
var txtFile = "getData.txt"
let file = fs.readFileSync(txtFile, 'utf8');
file.open("r"); // open file with read access
var str = "";
while (!file.eof) {
// read each line of text
str += file.readln() + "\n";
}
file.close();
alert(str);
Upvotes: 0
Views: 2540
Reputation: 72266
fs.readFileSync()
reads the entire contents of a file and returns it as string.
This code:
var txtFile = "getData.txt"
let str = fs.readFileSync(txtFile, 'utf8');
alert(str);
is enough to put on screen the content of the file.
Read more about the fs
module of node.js
.
Upvotes: 3