简体   繁体   中英

Error: Cannot find module 'data.json' Require stack: - C:

The json file is in the same directory as the index.js. Unfortunately i get an error.

Error: Cannot find module 'data.json'
Require stack: - C:\Users\yoan_\Desktop\train\project\index.js
const {render} = require('ejs');
const express = require('express');
const app = express();
const path = require('path');
const redditdata = require('data.json');

app.set('view enginge', 'ejs');
app.set('views', path.join(__dirname, '/views'));
app.get('/q/:term', (req, res) => {
  const {term} = req.params;
  const data = redditData[term];
  console.log(data);
});

app.listen('3000', () => {
  console.log('listening on port 3000');
});

This error:

Error: Cannot find module 'data.json'

is caused by this command:

const redditdata = require('data.json');

The require module loader will consider any path name that doesn't start with a "./" or a "/" to be a core module. It will not look in the local folder, so it will not find the 'data.json' file.

The fix: start the path name with a "./":

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

Better: Use `fs.readFileSync` to load JSON

Using require to read JSON data has a drawback: require caches the data it reads, so the JSON data your program gets may be out of date.

The recommended way to read a JSON file is with fs.readFileSync() .

const fs = require('fs');
const redditdata = JSON.parse(fs.readFileSync('./data.json'));

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