node.js 需要文件作为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12752622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
require file as string
提问by ThomasReggi
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.
我正在使用 node + express,我只是想知道如何将任何文件作为字符串导入。假设我有一个 txt 文件,我只想将它加载到一个变量中。
var string = require("words.txt");
I am against
我反对
modules.exports = function(){
var string = "whatever";
return string;
}
回答by Jonathan Lonowski
If it's for a (few) specific extension(s), you can add your own require.extensionshandler:
如果是(少数)特定扩展,您可以添加自己的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
Otherwise, you can mix fs.readFilewith require.resolve:
否则,您可以混合fs.readFile使用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);
});
回答by Max Ma
To read the CSS file to String, use this code. It works for .txt.
要将 CSS 文件读取为字符串,请使用此代码。它适用于.txt.
const fs = require('fs')
const path = require('path')
const css = fs.readFileSync(path.resolve(__dirname, 'email.css'), 'utf8')
ES6:
ES6:
import fs from 'fs'
import path from 'path'
let css = fs.readFileSync(path.resolve(__dirname, 'email.css'), 'utf8')
回答by Simon Boudrias
you'll have to use readFilefunction from filesystemmodule.
你必须使用模块中的readFile函数filesystem。
回答by cancerbero
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
你可以需要 .json 文件,包括 node.js 和 TypeScript。这是唯一支持 required() 适合序列化文本的格式。您可以使用编译时工具将文件打包成 json,例如https://github.com/cancerberoSgx/fs-to-json

