Node.js报错'file.open is not a function':本地文本文件转数组读取问题
'file.open is not a function' Error When Reading a Local File in Node.js Hey there! Let's break down why you're hitting this error and how to fix it so you can read your text file and parse it into an array smoothly.
The Root of the Problem
Your code uses fs.readFileSync(txtFile, 'utf8') which directly returns the full content of your file as a string — not a file object or handle. That's why calling file.open("r") throws an error: plain strings don't have an open method!
readFileSync already handles opening, reading, and closing the file in one step. You don't need to call open separately at all.
Correct Approach: Read and Parse the File Content
Here's how to adjust your code to read the file and convert its content into an array (we'll assume your file has one entry per line — tweak the separator if your data uses commas, spaces, etc.):
Synchronous Read (Matching Your Original Code Style)
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 file and parse to array const txtFile = "getData.txt"; // Read full file content as a string const fileContent = fs.readFileSync(txtFile, 'utf8'); // Split content into array, filter out empty lines to clean up data const dataArray = fileContent.split('\n').filter(line => line.trim() !== ''); // Now you can use dataArray for your logic! console.log(dataArray);
Asynchronous Read (Recommended for Node.js)
If you don't want to block your server while reading the file (better for performance in most cases), use the asynchronous fs.readFile instead:
// ... keep your existing imports ... const txtFile = "getData.txt"; fs.readFile(txtFile, 'utf8', (err, fileContent) => { if (err) { console.error('Oops, error reading the file:', err); return; } // Parse content to array const dataArray = fileContent.split('\n').filter(line => line.trim() !== ''); console.log(dataArray); });
When Would You Use fs.open?
If you ever need low-level control over file operations (like reading specific chunks of a file incrementally), you'd use fs.open or fs.openSync to get a file descriptor, then read/write with that descriptor. But for simple full-file reads, readFile/readFileSync is way simpler and cleaner.
For context, here's what the low-level approach would look like (though this is overkill for your use case):
const fd = fs.openSync(txtFile, 'r'); const buffer = Buffer.alloc(1024); const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, 0); const fileContent = buffer.toString('utf8', 0, bytesRead); const dataArray = fileContent.split('\n').filter(line => line.trim() !== ''); fs.closeSync(fd); // Don't forget to manually close the file!
内容的提问来源于stack exchange,提问作者Philip Miller

