orhankutlu orhankutlu - 6 months ago 19
Node.js Question

Nodejs "Unexpected token ." when creating object

I have tried to search my problem but I couldn't even know how to ask it. I looked similar questions but I couldn't find anything. So here is my problem.

I have two js files. First one is constant.js which keeps HTTP field names. Here is the code snippet of it

module.exports = {
USERNAME: 'username'

The second file is test.js and I would like to create some object inside of this file. While creating an object I would like to use constant.js file property names as shown in below:

var constant = require('./constant');

var x = {
constant.USERNAME: "test"


When i execute test.js I expected to see
{ username: 'test' }
in the console but I got this following error:

constant.USERNAME: "test"
SyntaxError: Unexpected token .
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3

I don't know why is it happening. Why can't I create my object? Any help would be greatly appreciated.

NOTE: Both files are on the same folder. There is no module export error. When I try to
it works well.


JS object literals (x = { ... }) consist of name: value pairs, where the name is a literal (and JS does not allow . in it), and you cannot use another variable here. To achieve what I think you want to achieve, I would do:

x = {};
x[constant.USERNAME] = "test";