最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Nodejs Curl result to file is not saving file - Stack Overflow

programmeradmin1浏览0评论

This works perfectly in terminal.

curl -H "Authorization: Bearer sknWtK4sRtd...." "; > exportedData.ndjson

How can I make this work with node? This doesn't save file or return error.

const { exec } = require('child_process');
    exec('curl -H "Authorization: Bearer sknWtK4sRt..." "; > mydataexported.ndjson');

I tried several solutions and curl libraries.

This works perfectly in terminal.

curl -H "Authorization: Bearer sknWtK4sRtd...." "https://mypropect.api.sanity.io/v2021-06-07/data/export/myDataset" > exportedData.ndjson

How can I make this work with node? This doesn't save file or return error.

const { exec } = require('child_process');
    exec('curl -H "Authorization: Bearer sknWtK4sRt..." "https://myproject.api.sanity.io/v2021-06-07/data/export/mydataset" > mydataexported.ndjson');

I tried several solutions and curl libraries.

Share Improve this question edited yesterday traynor 8,6823 gold badges15 silver badges28 bronze badges asked 2 days ago Leonel Matias DomingosLeonel Matias Domingos 2,0506 gold badges34 silver badges54 bronze badges 1
  • from where do you run the script, the file should be saved in process.cwd() location.. – traynor Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 0

I think as you should use "request" and "fs" libs instead of curl for perfect coding. Coz, you can't detect connect error or file permission and so on via curl lib.

const fs = require('fs');
const request = require('request');

// Define the URL you want to request
const url = 'https://jsonplaceholder.typicode.com/posts'; // Example URL

// Make a GET request to the URL
request(url, (error, response, body) => {
  if (error) {
    console.error('Error occurred:', error);
    return;
  }

  // Check if the request was successful (status code 200)
  if (response.statusCode === 200) {
    // Save the response data (body) to a file
    fs.writeFile('responseData.json', body, (err) => {
      if (err) {
        console.error('Error writing to file:', err);
      } else {
        console.log('Response data saved to responseData.json');
      }
    });
  } else {
    console.log('Request failed with status code:', response.statusCode);
  }
});

发布评论

评论列表(0)

  1. 暂无评论