Как переписать данный код на NodeJS?
$file = Yii::getAlias('@frontend') . '/web/files/ya-events/' . $id . '.csv';
//если файла нет, создаем
if (!file_exists($file)) {
$fp = fopen($file, "w");
fwrite($fp, "ClientId,Target,DateTime,Price,Currency\n");
fwrite($fp, $yaid . ",paid," . time() . "," . $bill->sum . ",RUB\n");
fclose($fp);
}
$authToken = 'ТОКЕН';
if (function_exists('curl_file_create')) {
$cFile = curl_file_create($file, 'text/csv', 'test.csv');
} else { //
$cFile = '@' . realpath($file);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => $cFile]);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-type: multipart/form-data; boundary=------------------------" . $authToken,
'Authorization: OAuth ' . $authToken
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
return $result;
Документация Яндекс:
https://yandex.ru/dev/metrika/doc/api2/practice/of...
Я пробую, но получаю ошибку:
string(202) "{"errors":[{"error_type":"invalid_uploading","message":"Не найден параметр запроса.","location":"file"}],"code":400,"message":"Не найден параметр запроса."}"
var dataYandex = '------------------------7zDUQOAIAE9hEWoV\n';
dataYandex += 'Content-Disposition: form-data; name="file"; filename="data.csv"\n';
dataYandex += "Content-Type: text/csv\n";
dataYandex += 'UserId,Target,DateTime,Price,Currency\n';
dataYandex += data.yandexData[0].ClientId+','+data.yandexData[0].Target+','+data.yandexData[0].DateTime+','+data.yandexData[0].Price+','+data.yandexData[0].Currency+'\n';
dataYandex += "--------------------------7zDUQOAIAE9hEWoV--";
let uploadFileForm = new FormData()
uploadFileForm.append('file', fs.createReadStream(data.file))
// request options
var requestOptions = {
url: data.url,
method: data.method,
body: uploadFileForm,
headers:
{
Authorization: 'OAuth Токен',
'Content-Type': 'multipart/form-data; boundary=--------------------------439864217372737605994368'
},
};