这只是Ania kubow的气候变化API中的一个例子。
我的问题是:我有一个这样的列表,但它更大更长。我想将该列表存储在另一个文件中,如“exampleList.js”,然后我想将其导入到我的main.js文件中。
const newspapers = [
{
name: 'cityam',
address: 'https://www.cityam.com/london-must-become-a-world-leader-on-climate-change-action/',
base: ''
},
{
name: 'thetimes',
address: 'https://www.thetimes.co.uk/environment/climate-change',
base: ''
},
{
name: 'guardian',
address: 'https://www.theguardian.com/environment/climate-crisis',
base: '',
},
{
name: 'telegraph',
address: 'https://www.telegraph.co.uk/climate-change',
base: 'https://www.telegraph.co.uk',
},
{
name: 'nyt',
address: 'https://www.nytimes.com/international/section/climate',
base: '',
},
{
name: 'latimes',
address: 'https://www.latimes.com/environment',
base: '',
},
]
然后我想在这里调用它,而不是写在同一个文件(main.js),我不想代码看起来混乱和太长。实际上,我有更多的列表(可能3个列表,每个列表有超过100个地址,基址,名称),我想把它们存储在不同的文件中。
app.get('/news/:newspaperId', (req, res) => {
const newspaperId = req.params.newspaperId
const newspaperAddress = newspapers.filter(newspaper => newspaper.name == newspaperId)[0].address
const newspaperBase = newspapers.filter(newspaper => newspaper.name == newspaperId)[0].base
axios.get(newspaperAddress)
.then(response => {
const html = response.data
const $ = cheerio.load(html)
const specificArticles = []
$('a:contains("climate")', html).each(function () {
const title = $(this).text()
const url = $(this).attr('href')
specificArticles.push({
title,
url: newspaperBase + url,
source: newspaperId
})
})
res.json(specificArticles)
}).catch(err => console.log(err))
})
我尝试创建一个列表文件,然后我尝试语句import
:
import exampleList from (./src/exampleList.js)
型
它说,我需要添加"type": "module"
到我的package.json.我这样做了,但它仍然不工作,它说,我不能从模块导入语句。我还试图运行应用程序与.mjs和--node-experimental ...
相同的事情,不工作。
2条答案
按热度按时间bmp9r5qi1#
首先,确保导出的是已有的列表,另外,我建议以JSON格式存储数据。
第二,关于你所面临的错误
将
"type": "module"
添加到package.json查看此question上的主要答案
nue99wik2#
const newspapers = ["hello"]; module.exports = newspapers;
使用此命令从文件中导出数据,使用const newspaper = require("./src/exampleList")
导入文件并可以使用其他文件中的数据。