Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require file as string

People also ask

What is require () in JavaScript?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

Can I use require in JS file?

With require , you can include them in your JavaScript files and use their functions and variables. However, if you are using require to get local modules, first you need to export them using module.


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);
});

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')

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

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


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();
    };