如何在Node.js v12.11.1中正确获取articles.js的数据?
The issue here is that your articles.js file isn't explicitly exporting the articles array—right now, it's just a local variable that other modules can't access. Here's how to fix it step by step:
Step 1: Add a Default Export to articles.js
Modify your articles.js file to export the array using ES module syntax:
const articles = [ {"title": "title1","content": "content1"}, {"title": "title2","content": "content2"}, {"title": "title3","content": "content3"} ]; export default articles;
Alternatively, you can export the array directly without assigning it to a variable:
export default [ {"title": "title1","content": "content1"}, {"title": "title2","content": "content2"}, {"title": "title3","content": "content3"} ];
Step 2: Verify Your Import Path (Already Correct!)
Your test.js import path includes the .js extension, which is required for relative imports in Node.js ES modules—good job on that. The line:
import articles from '../hello-world/src/data/articles.js';
is correct because it matches the default export we just added.
Why You Were Getting an Empty Object
When you import a module that doesn't have any exports, Node.js returns an empty module namespace object. Since your original articles.js didn't export anything, articles in test.js ended up being that empty object. Adding the export default statement makes the array available for import.
Test the Fix
Run your script again with:
node --experimental-modules test.js
You should now see the full array logged to the console.
内容的提问来源于stack exchange,提问作者zwl1619

