“为什么会出现这个错误?”TypeError: mkdirp is not a function””

huangapple go评论90阅读模式
英文:

Why does this error appear? "TypeError: mkdirp is not a function"

问题

以下是您提供的代码的翻译部分:

上述错误发生在我运行代码时因此文件创建过程不起作用请告诉我解决方案

此代码用于基于Naver Trend API和Naver Advertising API计算结果然后创建图形它分为两个文件服务器和插件密钥在另一个文件中创建并发送整个代码似乎没有问题但似乎模块未正确安装或文件路径错误我一直在寻找解决方案但找不到

// 代码部分已删除

我在本地服务器上运行了此代码但在输出结果后未完成后续任务

请注意,我已删除了代码中的敏感信息,如密钥等。如果您需要进一步的帮助或解决问题,您可以提出具体的问题或补充信息。

英文:

The above error occurred when I was running the code, so the process of creating the file is not working. Please let me know the solution.

This code is used to calculate the results based on the Naver Trend API and Naver Advertising API, and then create a graph. It is written in two files, server and addon, and the keys are created in another file and sent. The entire code seems to be fine, but it seems that the module is not installed properly or the file path is wrong. I've been looking for a solution, but I can't find it.

const request = require("request-promise");
const crypto = require("crypto");
const axios = require("axios");
const vega = require("vega");
const fs = require("fs");
const mkdirp = require("mkdirp");
const path = require("path");
const account = require("./account");
const spec = require("./default_chart_spec.json");
async function getClickRatios(keyword, date, device = "", gender = "") {
console.log("device : ", device);
let request_body = {
startDate: date[0],
endDate: date[1],
timeUnit: "month",
keywordGroups: [
{
groupName: "KW",
keywords: [keyword],
},
],
device: device,
gender: gender,
};
client_id = "";
client_secret = "";
let option = {
method: "POST",
uri: "https://openapi.naver.com/v1/datalab/search",
body: JSON.stringify(request_body),
headers: {
"X-Naver-Client-Id": client_id,
"X-Naver-Client-Secret": client_secret,
"Content-Type": "application/json",
},
};
let msg = await request(option);
let json = JSON.parse(msg);
return json;
}
async function getClickCnt(keyword, date) {
//코드는 getClickCnt라는 비동기 함수를 정의
client_id = "4jc3nDuSjniu9JXDkdbm";
client_secret = "Fk05DUQBH7";
const path = "/keywordstool";
const timestamp = new Date().getTime();
const msg = `${timestamp}.GET.${path}`;
const signature = crypto
.createHmac("SHA256", account.secretKey)
.update(msg)
.digest("base64");
//const formatted = keywords.map(e => e.keyword).join(',')
const option = {
method: "get",
url: `https://api.searchad.naver.com${path}`,
params: {
format: "json",
hintKeywords: keyword,
},
headers: {
"X-Timestamp": timestamp,
"X-Customer": account.customerId,
"X-API-KEY": account.accessLicense,
"X-Signature": signature,
},
};
//let data = await request(option);
return await axios(option);
}
//이 함수를 호출하면 지정된 키워드와 기간에 대한 클릭 수 데이터가 반환
function pad(n, width) {
n = n + "";
return n.length >= width ? n : new Array(width - n.length + 1).join("0") + n;
}
// pad 함수는 숫자 형식을 특정 너비로 패딩
function getDir(keyword, date, target) {
if (target === "directory_file") return path.join("chart_image", keyword);
if (target === "image_file")
return path.join("chart_image", keyword, date[2] + ".png");
}
//getDir 함수는 특정 목적에 따라 경로를 생성
//================================================================================
module.exports = {
async getClickRatios(keyword, date, device = "", gender = "") {
console.log("device : ", device);
let request_body = {
startDate: date[0],
endDate: date[1],
timeUnit: "month",
keywordGroups: [
{
groupName: "KW",
keywords: [keyword],
},
],
device: device,
gender: gender,
};
client_id = "";
client_secret = "";
let option = {
method: "POST",
uri: "https://openapi.naver.com/v1/datalab/search",
body: JSON.stringify(request_body),
headers: {
"X-Naver-Client-Id": client_id,
"X-Naver-Client-Secret": client_secret,
"Content-Type": "application/json",
},
};
let msg = await request(option);
let json = JSON.parse(msg);
return json;
},
async getClickCnt(keyword, date) {
client_id = "";
client_secret = "";
const path = "/keywordstool";
const timestamp = new Date().getTime();
const msg = `${timestamp}.GET.${path}`;
const signature = crypto
.createHmac("SHA256", account.secretKey)
.update(msg)
.digest("base64");
//const formatted = keywords.map(e => e.keyword).join(',')
const option = {
method: "get",
url: `https://api.searchad.naver.com${path}`,
params: {
format: "json",
hintKeywords: keyword,
},
headers: {
"X-Timestamp": timestamp,
"X-Customer": account.customerId,
"X-API-KEY": account.accessLicense,
"X-Signature": signature,
},
};
//let data = await request(option);
return await axios(option);
},
async getTrend(keyword, date) {
let click_ratio_json = await getClickRatios(keyword, date);
let info = await getClickCnt(keyword, date);
let data = info.data.keywordList[0];
click_info = [data.monthlyPcQcCnt, data.monthlyMobileQcCnt];
click_info[0] = click_info[0] == "< 10" ? 0 : click_info[0];
click_info[1] = click_info[1] == "< 10" ? 0 : click_info[1];
click_total = click_info[0] + click_info[1];
console.log("click_ratio : ", click_ratio_json.results[0].data);
console.log("click totla : ", click_total);
let click_per_ratio =
click_total / int(click_ratio_json.results[0].data[12]["ratio"]);
let click_trend = [];
for (let i = 0; i < 12; i++)
click_trend.push(
Math.ceil(
click_ratio_json.results[0].data[i]["ratio"] * click_per_ratio
)
);
return click_trend;
},
async getTrendp(keyword, date, device) {
let click_ratio_json;
if (device === "total")
click_ratio_json = await getClickRatios(keyword, date);
else if (device === "pc")
click_ratio_json = await getClickRatios(keyword, date, "pc");
else if (device === "mobile")
click_ratio_json = await getClickRatios(keyword, date, "mo");
console.log("fin");
let info = await getClickCnt(keyword, date);
let data = info.data.keywordList[0];
click_info = [data.monthlyPcQcCnt, data.monthlyMobileQcCnt];
click_info[0] = click_info[0] == "< 10" ? 0 : click_info[0];
click_info[1] = click_info[1] == "< 10" ? 0 : click_info[1];
console.log("click info : ", click_info);
if (device === "total") click_total = click_info[0] + click_info[1];
else if (device == "pc") click_total = click_info[0];
else if (device == "mobile") click_total = click_info[1];
console.log("click_ratio : ", device, click_ratio_json.results[0].data);
console.log("click_total : ", device, click_total);
let click_per_ratio =
click_total / click_ratio_json.results[0].data[11]["ratio"];
console.log("click_per_ratio : ", click_per_ratio);
let click_trend = [];
for (let i = 0; i < 12; i++)
click_trend.push(
Math.ceil(
click_ratio_json.results[0].data[i]["ratio"] * click_per_ratio
)
);
console.log("=========================");
return click_trend;
},
async veg2png(keyword, date) {
return new Promise(function (resolve, reject) {
let view = new vega.View(vega.parse(spec), {
renderer: "none",
}).initialize();
view
.toCanvas()
.then(function (canvas) {
console.log("Writing PNG to file...");
const directory_file_dir = getDir(
keyword,
date,
(target = "directory_file")
);
const image_file_dir = getDir(keyword, date, (target = "image_file"));
mkdirp(directory_file_dir, (err) => {
fs.writeFileSync(image_file_dir, canvas.toBuffer());
resolve();
});
})
.catch(function (err) {
console.log("Error writing PNG to file:");
console.error(err);
});
});
},
getDate(term = "1y") {
let today = new Date();
let before = new Date();
before.setYear(today.getFullYear() - 1);
let today_f =
today.getFullYear() +
"-" +
pad(today.getMonth() + 1, 2) +
"-" +
pad(today.getDate(), 2);
let before_f =
before.getFullYear() +
"-" +
pad(before.getMonth() + 1, 2) +
"-" +
pad(before.getDate(), 2);
let today2_f =
today.getFullYear() + "-" + pad(today.getMonth() + 1, 2) + "-" + "01";
return [before_f, today_f, today2_f];
},
getDir(keyword, date, target) {
if (target === "directory_file") return path.join("chart_image", keyword);
if (target === "image_file")
return path.join("chart_image", keyword, date[2] + ".png");
},
setChart(trends) {
console.log("setting Charing!");
spec.data[0].values = [];
for (let i = 0; i < 12; i++) {
// if dic (pc and mobile and all)
for (let j = 0; j < trends.length; j++) {
let graph_data = { x: i, y: trends[j][i], c: j };
spec.data[0].values.push(graph_data);
}
}
console.log("spec value : ", spec.data[0].values);
fs.writeFileSync("./default_chart.spec.json", JSON.stringify(spec));
console.log("write complie!!");
},
};

I deleted the secret key

const request = require("request-promise");
const express = require("express");
const fs = require("fs");
const asyncify = require("express-asyncify");
const app = asyncify(express());
const path = require("path");
const Addon = require("./Addon");
const port = 59239;
app.use(express.static(path.join(__dirname, "public")));
app.get("/keytool", async (req, res) => {
keyword = req.query.kw;
//let trend = Addon.getTrendp(keyword, date);
let date = Addon.getDate(); // [before, today, today(날짜가 1)];
console.log(date);
let dir = Addon.getDir(keyword, date, (target = "image_file"));
let exists = fs.existsSync(dir);
if (!exists) {
// if file is not exist
console.log("making graph!!");
let trend_pc = await Addon.getTrendp(keyword, date, (device = "pc"));
let trend_mobile = await Addon.getTrendp(
keyword,
date,
(device = "mobile")
);
let trend_all = await Addon.getTrendp(keyword, date, (device = "total"));
let trends = [trend_pc, trend_mobile, trend_all];
console.log("trends : ", trends);
Addon.setChart(trends);
Addon.veg2png(keyword, date).then(function () {
console.log("after veg2png");
//Addon.setChart(trend_all);
fs.readFile(dir, function (err, data) {
if (err) {
res.status(404).end();
console.log(err);
} else {
res.set("Content-Type", "image/png");
console.log("img data : ", data);
res.send(data);
}
});
});
} else {
//file is exist
console.log("graph already exist!!");
fs.readFile(dir, function (err, data) {
if (err) {
res.status(404).end();
console.log(err);
} else {
res.set("Content-Type", "image/png");
console.log(data);
res.send(data);
}
});
}
});
let server = app.listen(port, function () {
console.log("Server is Running at http://localhost:59239/keytool?kw=");
});

I ran this code on my local server, but the subsequent tasks were not completed after the output of the result.

答案1

得分: 1

查看文档

// 混合模块,import 或 require() 都可以工作
import { mkdirp } from 'mkdirp'
// 或:
const { mkdirp } = require('mkdirp')

导出是一个对象mkdirp 函数是该对象的属性。

您试图调用该对象本身,就好像它是一个函数一样。

英文:

Look at the documentation:

> // hybrid module, import or require() both work
> import { mkdirp } from 'mkdirp'
> // or:
> const { mkdirp } = require('mkdirp')

The export is an object. The mkdirp function is a property of that object.

You are trying to call the object itself as if it were a function.

huangapple
  • 本文由 发表于 2023年6月27日 19:45:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定