简体   繁体   English

file.open不是node.js中的函数。 文件读取

[英]file.open is not a function in node.js. file reading

I'm trying to read a local text file (not over web). 我正在尝试读取本地文本文件(不是通过Web)。 So, that I can parse it into a array. 因此,我可以将其解析为一个数组。 But I get the error: "file.open is not a function" 但是我得到了错误:“ file.open不是函数”

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);

fs.readFileSync() reads the entire contents of a file and returns it as string. fs.readFileSync()读取文件的全部内容,并将其作为字符串返回。

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 . 阅读有关node.jsfs模块的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM