0

this is my simple code.

const fs = require('fs');

try {
  const data = fs.readFileSync('file.txt', 'utf8');
  console.log(data);
} catch (err) {
  console.error(err);
}

whenever I run this I am getting following Error:

Error: "toString()" failed
    at stringSlice (buffer.js:558:43)
    at Buffer.toString (buffer.js:631:10)
    at Object.fs.readFileSync (fs.js:601:41)
    at Object.<anonymous> (C:\Users\admin\Desktop\Node Files\test.js:19:19)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)

I can figure out the problem. It because of file size.file size is 355MB. Buffer.toString fails because of exceeding the maximum supported length in V8.(>256MB) I am quite new in nodejs. how to solve this.can anyone please help

WALL-E
  • 5
  • 4
  • 1
    If you’re trying to just output the file contents in the console, you can use `fs.createReadStream(filename).pipe(process.stdout)` – Parzh from Ukraine Nov 15 '22 at 12:57
  • What are you actually trying to do with that file-content? Just logging out 300MB of textdata to the console does not make any sense. If we get to know, what you *really* want to do, we can suggest better options on how to handle that data – derpirscher Nov 17 '22 at 15:01
  • I am trying to replace string . that was not the main code which I posted here . If file size is <250 MB than it works fine and if file size> 250 MB than it gives that error – WALL-E Nov 17 '22 at 15:17
  • Then maybe something like this https://stackoverflow.com/questions/44265722/edit-large-file-in-node might help – derpirscher Nov 17 '22 at 16:10

1 Answers1

1

You maybe need to use a stream as in this precedent post : Node.js read big file with fs.readFileSync

Code in the post :

// Hash for buffer
let hash = crypto.createHash('md5'),

// Your file
stream = fs.createReadStream(file_path);

// Open the stream
stream.on('data', _buff => { hash.update(_buff, 'utf8'); });
...

Hope it's is working for your case