-5

I have been trying to move some variables to an external file so I decided to create a config.json

{
  "username":"...",
  "password":"...",
  "identity_secret":"...",
  "shared_secret":"...",
  "hostname":"127.0.0.1",
  "owner":"..."
}

And then require it as a module

'use strict'

var ACCEPT = 0xf
var REPORT = 0xff
var DECLINE = 0xfff

var fs = require('fs')
var config = require('./config.json')

But whenever I run the script I constantly get this error

module.js:457
  throw err;
  ^

Error: Cannot find module 'config.json'
  at Function.Module._resolveFilename (module.js:455:15)
  at Function.Module._load (module.js:403:25)
  at Module.require (module.js:483:17)
  at require (internal/module.js:20:19)
  at Object.<anonymous> (/root/steam-bot/steam_bot.js:8:14)
  at Module._compile (module.js:556:32)
  at Object.Module._extensions..js (module.js:565:10)
  at Module.load (module.js:473:32)
  at tryModuleLoad (module.js:432:12)
  at Function.Module._load (module.js:424:3)

I'm on node v6.4.0 with node bot.js

This is a single file script so I couldn't have had the chance to change the loading directory and both files are indeed in the same directory

It seems the import isn't throwing the error as this script works

var fs = require('fs')
var config = require('./config.json')

console.log(config.username)
ogtega
  • 62
  • 10

2 Answers2

1

There are two possible reasons you are getting that error. 1) Your JSON file is not in the same directory with your script or 2) You are using an old version of Node.js (before 0.5). Make sure your main script and JSON file is in the same directory. Also, if you don't want to update your Node.js, you can still include JSON file like this:

var imported = JSON.parse(require('fs').readFileSync('.\\config.json') + '');
  • 1
    He uses v6.4.0 he mentioned it – MatejMecka Aug 27 '16 at 12:10
  • 2
    @UnknownDeveloper I know, but I am also writting this for future users who get the same issue. Maybe my answer can help them. –  Aug 27 '16 at 12:12
  • Oh ok nice thinking! – MatejMecka Aug 27 '16 at 12:12
  • 1
    Neither of these reasons are the case – ogtega Aug 27 '16 at 12:13
  • This will not work if the current working directory is set elsewhere. Something like `path.join(__dirname, "./config.json")` works better – Tamas Hegedus Aug 27 '16 at 12:13
  • @TamasHegedus This is just an example. I assume OP has enough programming experience to know that. –  Aug 27 '16 at 12:15
  • 2
    @tolunlade If neither of these cases are your, you need to provide more informations about your problem and also let us know how to reproduce your error, otherwise I cannot say anything more than this. –  Aug 27 '16 at 12:20
0

I looked through the rest of the script and realized there was another polldata.json being parsed that is generated by a lib I'm using.

For some strange reason this being improper threw

Error: Cannot find module 'config.json'
ogtega
  • 62
  • 10