Languages
[Edit]
EN

Node.js - read file as text (UTF-8)

3 points
Created by:
Vanessa-Drake
688

In this article, we would like to show you how to read file as text using Node.js.

Quick solution:

const fs = require('fs');

const text = fs.readFileSync('/path/to/file.txt', 'utf-8');

or:

const fs = require('fs');

fs.readFile('/path/to/file.txt', 'utf-8', (error, text) => {
    // Something here ...
});

Note: to know different text encoding check this article.

 

Practical example

In this section you can find two examples that shows how to read example file.txt file as text. First example reads file.txt file synchronously and second one asynchronously.

Example file.txt file:

Line 1
Line 2
Line 3

 

Sync mode

Example index.js file:

const fs = require('fs');

try {
    const text = fs.readFileSync('file.txt', 'utf-8');
    console.log(text);
} catch (error) {
    console.error(text);
}

Output:

Line 1
Line 2
Line 3

 

Async mode

Example index.js file:

const fs = require('fs');

fs.readFile('file.txt', 'utf-8', (error, text) => {
    if (error) {
        console.error(error);  // or `throw error;`
    } else {
        console.log(text);
    }
});

Output:

Line 1
Line 2
Line 3

 

See also

  1. Node.js - supported text encoding

  2. Node.js - read files

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - file system module

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join