1

Here is my example:

var name="Doe";
var template = require('./template.txt');

and template.txt contains:

`hello ${name}`

I got the error: name is not defined.

Any idea ?

yarek
  • 8,962
  • 25
  • 93
  • 180
  • I think it is not possible as you put it, but template litereals might help you with what you want to do. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates – hazimdikenli Apr 02 '19 at 11:12
  • ok, but how to keep it external ? – yarek Apr 02 '19 at 11:21

2 Answers2

2

Well you literally want to take JS code from a .txt file and run it, so you need the infamous eval

var name="Doe";
var template = require('fs').readFileSync('./template.txt');
template = template.toString().trim();

console.log(eval(template)) // will output: hello Doe

Although it can be dangerous to run JS code like this, if the templates are files that are in your control and written by you, then I guess it can be done.

Ofcourse you could simply use a template engine like EJS or nunjucks

Alex Michailidis
  • 3,503
  • 1
  • 11
  • 30
1

From the Node.js documentation:

The module wrapper
Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following:

(function(exports, require, module, __filename, __dirname) { // Modulecode actually lives in here });

By doing this, Node.js achieves a few things:

  • It keeps top-level variables (defined with var, const or let) scoped to the module rather than the global object.
  • It helps to provide some global-looking variables that are actually specific to the module, such as:

    • The module and exports objects that the implementor can use to export values from the module.
    • The convenience variables __filename and __dirname, containing the module's absolute filename and directory path.

and globals:

In browsers, the top-level scope is the global scope. This means that within the browser var something will define a new global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside a Node.js module will be local to that module.

So when we define a variable in one module, the other modules in the program will not have access to that variable, but you can declare your variable without var and it will be defined as a global.

More info in this thread: Where are vars stored in Nodejs?

Fraction
  • 6,401
  • 3
  • 15
  • 34