By using the require() function, you can execute JS files in Node.js. The specific steps are as follows: Create a JS file, write the code and save it. In the Node.js file, use the require() function to load the JS file. Once the file is loaded, you can access the functions and variables defined in the JS file.
How to use Node.js to execute JS files
In Node.js, you can use require()
function to execute JS files.
Steps:
script.js
: <code class="js">console.log('Hello, world!');</code>
require()
function to load the JS file. File paths need to be relative to the current working directory. For example: <code class="js">const script = require('./script.js');</code>
console.log()
statement, you can use: <code class="js">script.console.log('Hello, world!');</code>
Details:
require()
The function returns an object containing all the values exported in the loaded JS file. require()
will return an empty object. require()
is also a caching mechanism, which means that files loaded once will not be loaded again. Example:
The following code example demonstrates how to execute a JS file in Node.js:
<code class="js">// 在脚本文件中定义了一个函数 // script.js function greet(name) { console.log(`Hello, ${name}!`); } // 在 Node.js 文件中加载脚本文件 // app.js const script = require('./script.js'); // 执行脚本文件中的函数 script.greet('John');</code>
The above is the detailed content of How nodejs executes js files. For more information, please follow other related articles on the PHP Chinese website!