我正在嘗試制作一個僅上傳特定 .extension 檔案的 CLI 例如,如果我想上傳.jpg檔案,那么只JPG應通過制作JPG檔案夾上傳檔案
const { program } = require("commander");
const fs = require("fs");
const path = require("path");
program.version("0.0.1");
program
.command("file")
.alias("f")
.description("Add filename with filepath")
.action(() => {
prompt(questions).then((answers) => {
try {
// compare extension
const extension = path.extname(answers.fileName);
const allowedExtension = ".jpg";
if (allowedExtension !== extension) {
console.log("Use only .jpg Extension file");
} else {
// make dir
fs.mkdir(path.join(__dirname, "JPG"), { recursive: true }, (err) => {
if (err) {
return console.error(err);
}
// read file or uploaded file
const file = fs.createReadStream(
`${answers.filePath}/${answers.fileName}`
);
console.log(
"Directory created successfully!",
answers.fileName,
answers.filePath
);
});
}
} catch (error) {
console.log(error.message);
}
});
});
program.parse(process.argv);
但不知道如何在提供的檔案夾中使用 CLI 上傳檔案
uj5u.com熱心網友回復:
使用 writeFile 函式上傳它:
const { program } = require("commander");
const fs = require("fs");
const path = require("path");
program.version("0.0.1");
program
.command("file")
.alias("f")
.description("Add filename with filepath")
.action(() => {
prompt(questions).then((answers) => {
try {
// compare extension
const extension = path.extname(answers.fileName);
const allowedExtension = ".jpg";
if (allowedExtension !== extension) {
console.log("Use only .jpg Extension file");
} else {
// make dir
fs.mkdir(path.join(__dirname, "JPG"), { recursive: true }, (err) => {
if (err) {
return console.error(err);
}
const file = fs.createReadStream(
`${answers.filePath}/${answers.fileName}`
);
fs.writeFile(`${answers.filePath}/${answers.fileName}`,file,(err) => console.log(err))
console.log(
"Directory created successfully!",
answers.fileName,
answers.filePath
);
});
}
} catch (error) {
console.log(error.message);
}
});
});
program.parse(process.argv);
uj5u.com熱心網友回復:
我從未使用過 nodeJs,所以這可能會也可能不會。您應該查找 scp 以在兩個源之間進行 cli 傳輸,您可以使用 npm 安裝 node-scp 模塊(或者我讀過)
npm i node-scp
然后,您需要匯入它,定義源路徑和目標路徑,然后使用它。
var local_folder_path = './local/dir';
var detination_folder_path = '/server/path';
send_folder_using_async_await(local_folder_path, detination_folder_path);
async function send_folder_using_async_await(folder_path,
destination_path)
{
try {
const client = await scp(remote_server)
await client.uploadDir(folder_path, destination_path)
client.close()
} catch (e) {
console.log(e)
}
}
像這樣的東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388220.html
標籤:javascript 节点.js 命令行 命令行界面 节点
下一篇:Discord.js:roles.some(r=>!message.member.roles.cache.has(r))不起作用
