require file as string Ask Question

require file as string Ask Question

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;

}

ベストアンサー1

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

おすすめ記事