skip to Main Content

I have this folder structure in my project. testproject/backend/amplify/backend/function/newestjavascript/src/index.js. And testproject/backend/src/amplifyconfiguration.json

I want to import amplifyconfiguration.json into my index.js file and use it. I am trying to use the require() statement from node, but it always tells me my amplifyconfiguration.json file cannot be found even though it clearly exists. I know my folder structure and spelling are not incorrect. Any idea why it will not import my amplifyconfiguration.json file?

Here is my code that does not work:

const { Amplify } = require('aws-amplify');
const { signUp } = require('aws- 
amplify/auth');
const amplifyConfig = 
const amplifyConfig = require("../../../../src/amplifyconfiguration.json");
exports.handler = async (event) => {
try {
  Amplify.configure(amplifyConfig);
}

This code gives me this error: "Cannot find module ‘../../../../src/amplifyconfiguration.json’"

2

Answers


  1. Here is how you can access your json file.

    const jsonData = require("../../../../src/amplifyconfiguration.json");
    

    I will refer you to visit on this medium doc and understand file paths

    Login or Signup to reply.
  2. Approach 1:
    It is likely that your script is being run outside of its current directory. In that case, you could try and update your require based on the result of console.log(__dirname).

    Approach 2: You could try using path.join instead as it will give you an absolute path to your configuration file. This is also good for debugging because you can check if the path is as you expect. Here is how you would use it:

    const pathToAmplifyConfig = path.join(__dirname, "..", "..", "..", "..", "src", "amplifyconfiguration.json");
    console.log(pathToAmplifyConfig); //This should show you the correct absolute path
    const config = JSON.parse(fs.readFileSync(pathToAmplifyConfig, 'utf8'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search