Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file one character at a time in node.js?

Tags:

stream

node.js

Is there a way to read one symbol at a time in nodejs from file without storing the whole file in memory? I found an answer for lines

I tried something like this but it doesn't help:

const stream = fs.createReadStream("walmart.dump", {
    encoding: 'utf8',
    fd: null,
    bufferSize: 1,
});
stream.on('data', function(sym){
    console.log(sym);
});
like image 830
kharandziuk Avatar asked May 07 '15 09:05

kharandziuk


People also ask

How do I read a text file in node JS?

We can use the 'fs' module to deal with the reading of file. The fs. readFile() and fs. readFileSync() methods are used for the reading files.

How do I read the next line in node JS?

Method 1: Using the Readline Module: Readline is a native module of Node. js, it was developed specifically for reading the content line by line from any readable stream. It can be used to read data from the command line. const readline = require('readline');

How do I read a text file line by line in node JS?

Here's the easiest way to read lines from a file, without any external modules: const fs = require('fs'); const readline = require('readline'); async function processLineByLine() { const fileStream = fs. createReadStream('input. txt'); const rl = readline.

How do I read the first line of a file in node?

In all current versions of Node. js, readline. createInterface can be used as an async iterable, to read a file line by line - or just for the first line. This is also safe to use with empty files.


1 Answers

Readable stream has a read() method, where you can pass the length, in bytes, of every chunk to be read. For example:

var readable = fs.createReadStream("walmart.dump", {
    encoding: 'utf8',
    fd: null,
});
readable.on('readable', function() {
  var chunk;
  while (null !== (chunk = readable.read(1) /* here */)) {
    console.log(chunk); // chunk is one byte
  }
});
like image 194
vanadium23 Avatar answered Oct 21 '22 08:10

vanadium23