136

I'm using node + express and I am just wondering how I can import any file as a string. Lets say I have a txt file all I want is to load it into a variable as such.

var string = require("words.txt");

I am against

modules.exports = function(){

    var string = "whatever";

    return string;

}
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • 1
    It's not an answer, but this avoids creating a function: `const { string } = require('words.js');` where `words.js` contains `module.exports = { string: 'whatever' };` – Dem Pilafian Aug 25 '17 at 20:51

6 Answers6

157

If it's for a (few) specific extension(s), you can add your own require.extensions handler:

var fs = require('fs');

require.extensions['.txt'] = function (module, filename) {
    module.exports = fs.readFileSync(filename, 'utf8');
};

var words = require("./words.txt");

console.log(typeof words); // string

Otherwise, you can mix fs.readFile with require.resolve:

var fs = require('fs');

function readModuleFile(path, callback) {
    try {
        var filename = require.resolve(path);
        fs.readFile(filename, 'utf8', callback);
    } catch (e) {
        callback(e);
    }
}

readModuleFile('./words.txt', function (err, words) {
    console.log(words);
});
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • 66
    require.extensions is now deprecated for anyone who comes across this post. http://nodejs.org/api/globals.html#globals_require_extensions – blockloop Jul 17 '13 at 18:35
  • 2
    `Deprecated in the past` but `Since the module system is locked, this feature will probably never go away. However, it may have subtle bugs and complexities that are best left untouched.` – loretoparisi Nov 09 '16 at 19:03
  • 17
    While it is indeed deprecated, is there any good alternative? (that extends require, I mean) – Gian Marco Toso Aug 02 '17 at 08:35
60

To read the CSS file to String, use this code. It works for .txt.

const fs = require('fs')
const path = require('path')

const css = fs.readFileSync(path.resolve(__dirname, 'email.css'), 'utf8')

ES6:

import fs from 'fs'
import path from 'path'

let css = fs.readFileSync(path.resolve(__dirname, 'email.css'), 'utf8')
Steffan
  • 704
  • 1
  • 11
  • 25
Max Ma
  • 1,060
  • 9
  • 15
  • 5
    How can I get this done for an html file? i have an html file in a sibling directory that i need to read and load as a string into cheerio? – lopezdp Nov 03 '19 at 18:38
  • 1
    It works exactly the same for an html file: const html = fs.readFileSync(path.resolve(__dirname, '../path/to/file.html'), 'utf8'); – Sean Dvir Aug 02 '21 at 08:00
10

The selected answer is deprecated and not recommended anymore. NodeJS documentation suggests other approaches like:

loading modules via some other Node.js program

but it does not expand any more.

  • You can use a very simple library like this: require-text

  • Or implement it yourself ( like from the package above: )

    var fs = require('fs');
    module.exports = function(name, require) {
       return fs.readFileSync(require.resolve(name)).toString();
    };
    
mim
  • 1,301
  • 14
  • 24
7

you'll have to use readFile function from filesystem module.

http://nodejs.org/docs/v0.3.1/api/fs.html#fs.readFile

Simon Boudrias
  • 42,953
  • 16
  • 99
  • 134
4

My simplest solution is

var string = require("fs").readFileSync("file.txt", 'utf8')
console.log("string = ", string);
0

you can require .json files, both with node.js and TypeScript. That's the only format that support being required() suitable for serializing text. YOu can use a compile-time tool to pack your files into a json, such as https://github.com/cancerberoSgx/fs-to-json

cancerbero
  • 6,799
  • 1
  • 32
  • 24