简体   繁体   中英

How to make local .json file accessible from remote machine or folder?

In my program I have.json file that is stored in my local folder. I also have Javascript code in the same folder that accessing this.json file and reads it's values. To access the file I am using:

const data = require('../JS/countries.json'); .

The program works perfectly on my local machine, and I have published it on github repository( https://github.com/TheRadioDept/technical-question ). However, after I tried cloning this repository into another folder, I faced an error:

code: 'MODULE_NOT_FOUND',
requireStack: [ '/home/me/progs/clonedRepo/technical-question/main.js' ]

[ '/home/me/progs/clonedRepo/technical-question/main.js' ] is the path to cloned repository, it is not original storage of.json file and javascript code. That means that code can only be executed on my local machine from the original folder where I store my JS and JSON files. Is there a way I can run this code and access it in another folder or computer?

main.js is at the root of your repository. The import

const data = require('../JS/countries.json');

depends on the name of the folder containing your repository. Usually the name of the folder and the name of your repository are similar. That means that most users clone your repository into a folder technical-question and the import fails.

You can remove this dependency with

const data = require('./countries.json');

Now, the name of the parent folder isn't used in the import.

try npm install in your terminal (npm is a package manager). This will install all the modules needed for your project with the help of package.json file which is probably already present in your project. In package.json you can find all the dependancies for your project and npm is going to install all of them in a new folder named node_modules. Hope this makes sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM