如何将API Fetch请求结果写入本地文件而非控制台输出
如何将Fetch请求的响应写入当前目录下的JSON文件(而非输出到控制台)
用户提供的可正常在控制台打印结果的代码:
const sample = fetch('https://dummyapi.io/data/v1/user?limit=5&page=1', { method: 'GET', headers: { 'app-id': '63e798a1498c3c5fa3e2faeb', }, }) .then(response => response.json()) .then(json => console.log(json));
用户尝试写入文件的代码(生成空{}文件):
const obj = fetch('https://dummyapi.io/data/v1/user?limit=5&page=1', { method: 'GET', headers: { 'app-id': 'xxxxxx', }, }) const fs = require('fs'); fs.writeFile("test.json", JSON.stringify(obj), function(err) { if(err) { return console.log(err); } console.log("The file was saved!"); });
问题原因
fetch函数返回的是一个Promise对象,不是直接的响应数据。直接对这个Promise对象执行JSON.stringify(),得到的就是{}——因为Promise本身的可序列化属性为空。必须等待Promise完成,拿到真正的响应JSON数据后,才能写入文件。
正确的JSON写入方案
方案1:使用.then链式调用延续原有写法
把文件写入逻辑放在response.json()之后的.then回调里,确保拿到真实数据再执行写入:
const fs = require('fs'); fetch('https://dummyapi.io/data/v1/user?limit=5&page=1', { method: 'GET', headers: { 'app-id': '63e798a1498c3c5fa3e2faeb', }, }) .then(response => response.json()) .then(jsonData => { // 写入Newfile.json fs.writeFile('./Newfile.json', JSON.stringify(jsonData, null, 2), (err) => { if (err) { console.error('写入JSON文件失败:', err); return; } console.log('JSON文件写入成功'); }); }) .catch(err => console.error('请求失败:', err));
JSON.stringify(jsonData, null, 2)里的第三个参数2用来格式化JSON内容,让文件更易读,可根据需求调整。
方案2:使用async/await写法(更直观)
用async/await处理异步流程,代码结构更清晰:
const fs = require('fs').promises; // 使用promise版本的fs,避免回调嵌套 async function fetchAndSaveData() { try { const response = await fetch('https://dummyapi.io/data/v1/user?limit=5&page=1', { method: 'GET', headers: { 'app-id': '63e798a1498c3c5fa3e2faeb', }, }); const jsonData = await response.json(); // 写入JSON文件 await fs.writeFile('./Newfile.json', JSON.stringify(jsonData, null, 2)); console.log('JSON文件写入成功'); } catch (err) { console.error('操作失败:', err); } } fetchAndSaveData();
后续写入CSV文件的思路
要把JSON数据转成CSV,需要先提取数据中的字段,再拼接成CSV格式:
- 手动处理(适合简单数据):
// 承接上面的async/await代码,拿到jsonData后 const users = jsonData.data; // 假设接口返回的用户数据在data字段下 // 定义CSV表头 const headers = ['id', 'firstName', 'lastName', 'email']; // 转换每一行数据 const rows = users.map(user => headers.map(header => `"${user[header]}"`).join(',')); // 拼接表头和行数据 const csvContent = [headers.join(','), ...rows].join('\n'); // 写入CSV文件 await fs.writeFile('./Newfile.csv', csvContent); console.log('CSV文件写入成功'); - 使用第三方库(适合复杂数据):
可以安装csv-writer库简化操作:
示例代码:npm install csv-writerconst { createObjectCsvWriter } = require('csv-writer'); // 承接上面的jsonData const csvWriter = createObjectCsvWriter({ path: './Newfile.csv', header: [ {id: 'id', title: 'ID'}, {id: 'firstName', title: 'FIRST_NAME'}, {id: 'lastName', title: 'LAST_NAME'}, {id: 'email', title: 'EMAIL'} ] }); await csvWriter.writeRecords(jsonData.data); // jsonData.data是用户数组 console.log('CSV文件写入成功');
内容的提问来源于stack exchange,提问作者Brandon Winn
相关产品推荐
相关产品推荐

