how do I export/import a variable in nodejs?
with CommonJS modules (the Node.js default) you can export a variable by assigning to exports
, and import it via require()
:
// bar.js
exports.variable = 'value';
// foo.js
const { variable } = require('./bar');
if you're using ECMAScript modules, the keywords import
and export
do these:
// bar.js
export const variable = 'value';
// foo.js
import { variable } from './bar';
nodejs import dynamic variable from another file
put your variable inside of a function that returns the variable then export the function
export function getVariable(){
let myVar = 0;
return myVar
}
module.exports = getVariable;
const getVar = require('../file.js');
Is it possible to import variables in JavaScript (node.js)?
I could assign a local variables for every property export&required module G object, but obviously it's a tedious process to add every variable to the test file manually to correspond the G objects.
No, that's how it is supposed to work. You - and only you - are in charge of what local variables exist in your module scope. No changes in the "export variables" of an included module should break your code.
Accessing properties on the imported module (with a self-chosen name) is the way to go. This is quite equivalent to Python's import app
or import app as g
.
If you want some particular properties as local variables, you will usually choose them manually, as in Python's from app import DATA, F1
. In JS, you will need a multiple var
statement like the one you've shown in your question. However, there is a syntax feature called destructuring assignment which will make this more fluid. You can use this in JavaScript 1.7+ (Gecko), CoffeeScript, or EcmaScript 6:
var {DATA, F1} = require("app.js");
Is there any way to do this automatically?
Yes and No. You should not do this, but you can - just like Python's frowned-upon from app import *
. To cite what they say, which is equally true for JavaScript:
[It] introduces an unknown set of names into the interpreter, possibly
hiding some things you have already defined.Note that in general the practice of importing
*
from a module or
package is frowned upon, since it often causes poorly readable code.
However, it is okay to use it to save typing in interactive sessions.
In JavaScript, you can[1] use the with
-statement:
with (require("app.js")) {
…
}
[1]: Not in ES5.1 strict mode, though - which is recommended for optimisation
How to perform a “variable” ES6 import?
Not with the import
statement. import
and export
are defined in such a way that they are statically analyzable, so they cannot depend on runtime information.
You are looking for the loader API (polyfill), but I'm a bit unclear about the status of the specification:
System.import('./utils/' + variableName).then(function(m) {
console.log(m);
});
Read/Use variables from another javascript file
I figured it out, in file1 I can export variables like this :
function thisIsAFunction() {
let var1 = { qty: 123 }
let var2 = { qty: 123 }
let var3 = { qty: 123 }
return [ var1, var2, var3 ];
}
module.exports = {
thisIsAFunction
}
Then read/use the first variable like this:
let importedValue= importedFunct.thisIsAFunction()
console.log( importedValue[0][0].qty)
How to access variable in another file in node js
I created a small node app to test a variation of your code. Two important findings:
1.
const import = require('./export');
import
is reserved (as well as export
). Node will throw a SyntaxError: Unexpected token
if you attempt to use either one as a variable name.
2.
console.log(import.count);
In your code, you're attempting to log a variable that's already been returned. You'll notice the log statement will return undefined
. Instead, create a function that you can call to get the value from the actual variable in the other file.
To make things clearer, here's a little demo to show these concepts in action.
export.js
let count;
const setCount = num => count = num;
const getCount = () => count;
// Shortcut: If the key: value is the same, we can just omit the value
module.exports = {
setCount,
getCount
}
server.js
const ex = require('./export');
ex.setCount(5);
console.log(ex.getCount()); // 5
How to get a variable from a file to another file in Node.js
Edit (2020):
Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.
- For Node v13.9.0 and beyond, experimental modules are enabled by default
- For versions of Node less than version 13.9.0, use
--experimental-modules
Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:
- Files ending in
.mjs
.- Files ending in
.js
when the nearest parentpackage.json
file contains a top-level field"type"
with a value of"module"
.- Strings passed in as an argument to
--eval
or--input-type=module
.
Once you have it setup, you can use import
and export
.
Using the example above, there are two approaches you can take
./sourceFile.js:
// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default.
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary.
// You can actually omit declaring what variableName is here.
// { variableName } is equivalent to { variableName: variableName } in this case.
export default { variableName: variableName }
./consumer.js:
// There are three ways of importing.
// If you need access to a non-default export, then
// you use { nameOfExportedVariable }
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'
// Otherwise, you simply provide a local variable name
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'
./sourceFileWithoutDefault.js:
// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'
./consumer2.js
// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'
console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'
// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'
// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }
// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue
You can re-export anything from another file. This is useful when you have a single point of exit (index.{ts|js}
) but multiple files within the directory.
Say you have this folder structure:
./src
├── component
│ ├── index.js
│ ├── myComponent.js
│ └── state.js
└── index.js
You could have various exports from both store.js and my-component.js but only want to export some of them.
./src/component/myComponent.js:
import createState from "./state";
export function example(){ };
./src/component/state.js:
export default function() {}
./src/component/index.js
export { example as default } from "./myComponent";
export * from "./myComponent"
./src/index.js
export * from "./component"
Original Answer:
You need module.exports:
Exports
An object which is shared between all instances of the current module
and made accessible through require(). exports is the same as the
module.exports object. See src/node.js for more information. exports
isn't actually a global but rather local to each module.
For example, if you would like to expose variableName
with value "variableValue"
on sourceFile.js
then you can either set the entire exports as such:
module.exports = { variableName: "variableValue" };
Or you can set the individual value with:
module.exports.variableName = "variableValue";
To consume that value in another file, you need to require(...)
it first (with relative pathing):
const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);
Alternatively, you can deconstruct it.
const { variableName } = require('./sourceFile');
// current directory --^
// ../ would be one directory down
// ../../ is two directories down
If all you want out of the file is variableName
then
./sourceFile.js:
const variableName = 'variableValue'
module.exports = variableName
./consumer.js:
const variableName = require('./sourceFile')
Related Topics
Submitting Rails Form on a Radio Button Selection
What Does It Mean That JavaScript Is a Prototype Based Language
Rails Specify Load Order of JavaScript Files
Can Nokogiri Interpret JavaScript? - Web Scraping
Uint8Array to String in JavaScript
How to Set Bootstrap Navbar Active Class with Angular Js
How to Get Objects Value If Its Name Contains Dots
Convert Array of Strings into an Array of Objects
Get Element at Specified Position - JavaScript
How to Wait in Node.Js (Javascript)? L Need to Pause for a Period of Time
The Definitive Best Way to Preload Images Using JavaScript/Jquery
How to Use Componentwillmount() in React Hooks
Is There a Version of JavaScript's String.Indexof() That Allows for Regular Expressions
Creating Range in JavaScript - Strange Syntax
How to Get the Content of the File Specified as the 'Src' of a <Script> Tag