skip to Main Content

With all of the updates to JavaScript in the last few years, is there a way to read a text file into a string with one line of code?

Something like:

var data = await fetch(url).data; 

2

Answers


  1. You have to call response.text() to get the contents returned from fetch().

    let data = await fetch(url).then(res => res.text())
    
    Login or Signup to reply.
  2. It seems you mean "local file" because you mentioned "file" and "read".

    It has always been one line excluding import.

    import { readFile } = require('fs/promises');
    const data = await readFile("path/to/file.txt", "utf8");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search