要求文件为字符串


99

我正在使用node + express,我只是想知道如何将任何文件导入为字符串。可以说我有一个txt文件,我想要的只是将其加载到这样的变量中。

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

我反对

modules.exports = function(){

    var string = "whatever";

    return string;

}

1
这不是答案,但这避免了创建函数:const { string } = require('words.js');where words.jscontainsmodule.exports = { string: 'whatever' };
Dem Pilafian

Answers:


127

如果是针对(少数)特定扩展名的,则可以添加自己的require.extensions处理程序:

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

否则,您可以fs.readFilerequire.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);
});

51
现在,此帖子中遇到的任何人都不再需要require.extensions。nodejs.org/api/globals.html#globals_require_extensions
blockloop

2
Deprecated in the past但是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

10
虽然确实不建议使用,但是还有什么好的选择吗?(这意味着需要扩展)
juandemarco

31

要将CSS文件读取为String,请使用此代码。它适用于.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')

2
如何为html文件完成此操作?我在兄弟目录中有一个html文件,我需要读取该文件并将其作为字符串加载到cheerio中?
lopezdp



0

所选答案已弃用不再建议使用。NodeJS文档建议了其他方法,例如:

通过其他Node.js程序加载模块

但它不再扩展。

  • 您可以使用一个非常简单的库,如下所示:require-text

  • 或自己实现(例如从上面的包中:)

    var fs = require('fs');
    module.exports = function(name, require) {
       return fs.readFileSync(require.resolve(name)).toString();
    };
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.