0

I have some data stored in an array in javascript and want to use that array in node js. I tried this:

JS:

let myArray = ['data1', 'data2'];

Node js:

let myArray = require('scripts.js').myArray;

But I get Error: Cannot find module error.

What should I do?

4
  • You should tell use where 'scripts.js' is on the file system relative to your Node script. Commented Dec 9, 2017 at 1:53
  • The node.js file is in root and scripts.js is in public/scripts/scripts.js I think there's no problem in path. @Mark_M Commented Dec 9, 2017 at 1:55
  • perhaps you need to export the variable first. Commented Dec 9, 2017 at 1:59
  • Then you have to require './public/scripts/scripts'. Or './scripts' if the file was in the root folder. Notice the dot in the front of the string. Commented Dec 9, 2017 at 2:01

1 Answer 1

1

You are using the syntax to import a node module: e.g.

const app = require('express')

Node is looking for a node module named script.js

If you want to require local files you need to use the syntax

let myArray = require('./scripts').myArray;

No need to put the .js on the end require does this for you. The full details in the documentation are here: https://nodejs.org/api/modules.html#modules_modules

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.