简体   繁体   English

错误:找不到模块“data.json”需要堆栈:-C:

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

The json file is in the same directory as the index.js. json 文件与 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. require模块加载器会将任何不以“./”或“/”开头的路径名视为核心模块。 It will not look in the local folder, so it will not find the 'data.json' file.它不会在本地文件夹中查找,因此不会找到“data.json”文件。

The fix: start the path name with a "./":修复:以“./”开头的路径名:

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

Better: Use `fs.readFileSync` to load JSON更好:使用 `fs.readFileSync` 加载 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.使用require读取 JSON 数据有一个缺点: require会缓存它读取的数据,因此您的程序获取的 JSON 数据可能已过期。

The recommended way to read a JSON file is with fs.readFileSync() .读取 JSON 文件的推荐方法是使用fs.readFileSync()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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