I'm trying to make a discord bot that can output certain data from my JSON file, and my project structure looks like this.
Project
|
+-- data/
| |
| +-- compSciCourses.json
|
+-- src/
| |
| +-- search.js
| +-- bot.js
|
+-- test/
| |
| +-- test.js
|
+-- .env
|
+-- package.json
|
+-- package-lock.json
Using search.js, I'm trying to read JSON data with the fs.readFileSync()
like this
// src/search.js
const fs = require('fs');
let rawdata = fs.readFileSync("../data/compSciCourses.json")
let courseData = JSON.parse(rawdata)
const findClass = (input) => {
// Some code
}
module.exports = { findClass }
I'm trying to call the function findClass
from my bot.js
// src/bot.js
const { Client } = require('discord.js')
const search = require('./search')
const client = new Client()
...
client.on('message', (message) => {
...
if (CMD_NAME === 'find') {
if (args.length === 0)
return message.reply("Please provide course name")
else
return message.reply(search.findClass(args))
}
}
})
...
When I run this with node src/bot.js
, I got this error.
fs.js:114
throw err;
^
Error: ENOENT: no such file or directory, open '../data/compSciCourses.json'
at Object.openSync (fs.js:443:3)
at Object.readFileSync (fs.js:343:35)
at Object.<anonymous> (/Users/michaelchang/Desktop/Programming Playground/Machine Learning/ChatBots/discordBot/courseNavigator/src/search.js:3:18)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! coursenavigator@1.0.0 start: `node ./src/bot.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the coursenavigator@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/michaelchang/.npm/_logs/2020-09-01T00_25_12_050Z-debug.log
I don't understand how I get this error because I already specified the JSON file at the right directory. Can someone please help me???
You can resolve the path relative the location of the source file - rather than the current directory - using path.resolve:
const path = require("path");
const file = fs.readFileSync(path.resolve(__dirname, "../data/compSciCourses.json"));
Faced this issue in my project I solved it just by importing the.json file
const data = require("../data/compSciCourses.json")
your IDE might give you autocompletion for the path:)
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.