require file as string

2019-01-23 10:33发布

问题:

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


回答2:

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


回答3:

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

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



回答4:

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