Asked 7 years ago
17 Nov 2017
Views 1127
angeo

angeo posted

how to include js file to node js file ?

setting.js

var defaultUrl="http://arrayoverflow.com";


i want to include setting.js file into tool.js

tool.js

const request = require('request');
// here need to acess the defaultUrl 
chirag

chirag
answered Apr 24 '23 00:00

In order to include a JavaScript file in a Node.js file, you can use the built-in require () function.

First, create a JavaScript file that you want to include in your Node.js file. For example, let's say you have a file named utils.js that contains some utility functions you want to use in your Node.js application.



// utils.js
function add(a, b) {
  return a + b
}

function multiply(a, b) {
  return a * b
}

module.exports = {
  add,
  multiply
}

In the example above, the add and multiply functions are exported using the module.exports object, which can then be used in other files that include utils.js.

Now, in your Node.js file, you can us e require() to include the utils.js file :



const utils = require('./utils.js')

console.log(utils.add(2, 3)) // Output: 5
console.log(utils.multiply(2, 3)) // Output: 6

In the example above, the utils object is imported using require(), and then the add and multiply functions are called using the utils object.

Note that the path to the file is relative to the current file. In this example, the utils.js file is in the same directory as the Node.js file, so the path is ' ./utils.js'. If the file is in a different directory, you would need to specify the relative path from the current file.

That's it! You can use require() to include any number of JavaScript files in your Node.js application, as long as they export the functionality you need using module.exports.
Post Answer