How to import a text file in a NodeJS app with TypeScript and ts-node in dev mode?

Viewed 412

I have a NodeJS/Express app that I'm developing using TypeScript, Nodemon and ts-node. In this app I have a .txt file containing some (long) text. I'm trying to read the content of the file and just log it to the console in dev mode.

import MyText from "./something.txt";

export const runIt = () => {
    console.log(MyText);
};

I'm importing the file directly (instead of using fs) because of a business requirement for keeping the number of deployed files to a minimum, which means that I have to bundle the code using Webpack and the text file is loaded with:

module.exports = {
    /*...*/
    module: {
        rules: [
            {
                test: /\.txt/,
                type: 'asset/source'
            }
        ]
    }
}

This works: running the backend.js bundle correctly "loads" the file and logs its content.

The problem comes in dev mode. When I start the dev server using ts-node --files ./src/server.ts I get a SyntaxError: Unexpected identifier because it's trying to parse the content of the .txt file as a module (from what I can deduce...).

What additional configuration am I missing? Is there a solution for this scenario? Is there an alternative for reading text (from) files that works well even after bundling?

Here's a codesandbox that reproduces my problem.

1 Answers

During dev you can register a module loader

// txt.js
/**
 * 
 * Allow import/require raw text file
 */
const fs = require('fs')
require.extensions[".txt"]= (m, fileName)=> {
  return m._compile(`module.exports=\`${fs.readFileSync(fileName)}\``, fileName);
}

launch it like this

node -r ts-node/register -r ./txt.js src/server.ts

https://stackblitz.com/edit/node-2zunvu

Related