your programing

문자열로 파일 필요

lovepro 2020. 10. 5. 20:31
반응형

문자열로 파일 필요


node + express를 사용하고 있으며 파일을 문자열로 가져올 수있는 방법이 궁금합니다. 내가 원하는 것은 변수에로드하는 것뿐입니다.

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

나는 반대한다

modules.exports = function(){

    var string = "whatever";

    return string;

}

(몇 가지) 특정 확장에 대한 경우 고유 한 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.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);
});

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

모듈의 readFile함수 를 사용해야 합니다 filesystem.

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


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

참고URL : https://stackoverflow.com/questions/12752622/require-file-as-string

반응형