javad
3 سال پیش توسط javad مطرح شد
0 پاسخ

مشکل در import فایل در node js

با سلام و خسته نباشید. بنده برای import فایل که با نود جی اس نوشتم مشکلی دارم و به خطا میخورم. که نمیدونم این مشکل از چیه. کدها رو قرار میدم لطفا اگر کسی میدونه مشکل از چیه کمک کنه تا حلش کنم.ممنون..
کدهای سمت فرانت:

const inputFile = useRef(null);
  const uploadFile = (event) => {
    let file = event.target.files[0];
    console.log('file',file);
    if (file) {
      let data = new FormData();
      console.log('d1',data);
      data.append('file', file);

      axios.post(`${Config.api_url}/rules/import`, data)
        .then((res) => {
          console.log(res);
          loadRules()
          addToast(
            'Emport successfully',
            `Rule was emport successfully`,
            'success'
          );
        }).catch((e) => {
          console.log(e);
          addToast(
            'Connection Error',
            `${e}`,
            'danger'
          );
        })
    }
  }
<input onChange={(e) => uploadFile(e)} type="file" accept=".zip" multiple style={{ display: "none" }} ref={inputFile}></input>
                <EuiButton
                  color="primary" iconType="importAction" onClick={() => { inputFile.current.click() }} >
                  Import
                </EuiButton>

این هم کدهای سمت سرور که با نود جی اس نوشتم

  router.post(
    {
      path: '/api/apk_alert/rules/import', 
      validate: { body: schema.maybe(schema.any()) },
      options: {
        body: {
          output: 'stream',
          parse: true,
          accepts: 'multipart/form-data', 
          // maxBytes: 500 * 1000 * 1000,
        },
      },
    },
    async (context, request, response) => {
      console.log('import_rules');

      try {
        return new Promise(function (resolve, reject) {
          const data = request.body;

          if (data.file) {

            if (fs.existsSync('/tmp/import_apk_alert')) {
              deleteFolderRecursive('/tmp/import_apk_alert/');
              console.log('ok ta inaja');
            } else {
            }
            fs.mkdirSync('/tmp/import_apk_alert');

            console.log(data.file);

            const name = data.file.hapi.filename;
            // const name = 'test';
            const path = `/tmp/import_apk_alert/${name}`; 
            const file = fs.createWriteStream(path);

            data.file.pipe(file);

            data.file.on('end',async () => {
              console.log('end');

              var stats = fs.statSync(path)
              console.log('state',stats);

              var fileSizeInBytes = stats["size"]
              console.log('fileSizeInBytes',fileSizeInBytes);

              //Convert the file size to megabytes (optional)
              var fileSizeInMegabytes = fileSizeInBytes / 1000000.0
              console.log('fileSizeInMegabytes:',fileSizeInMegabytes);

              const extract = require('extract-zip')
              async function main() {
                try {

                  console.log('exe name', name);

                  await extract(`/tmp/import_apk_alert/${name}`, { dir: `/tmp/import_apk_alert/rules` })
                  console.log('Extraction complete')
                  const { exec } = require('child_process');
                  // setTimeout(() => {
                  let all_rule = []
                  await fs.readdir('/tmp/import_apk_alert/rules', (err, files) => {

                    console.log({files})

                    if (err)
                      console.log(err);
                    else {
                      console.log("\nCurrent directory filenames:");
                      async function elastic() {
                        console.log('all_rule', all_rule);
                        const body = all_rule.reduce((acc, item) => acc.concat([{ index: { _index: ruleIndex, _id: item.rule_uuid } }, item]), []);
                        console.log('body', body);
                        try {
                          let ruleValue = await client.bulk({
                            index: ruleIndex,
                            refresh: 'wait_for',
                            body
                          })
                          resolve('true')
                        } catch (error) { 
                          reject('false')
                        }
                      }

                      files.forEach((file, index) => {
                        console.log({file})
                        exec(`base64 -d /tmp/import_apk_alert/rules/` + file.split(' ').join('\\ '), (error, stdout, stderr) => {
                          if (error) {
                            console.error(`exec error: ${error}`);
                            return;
                          }
                          console.log(JSON.parse(stdout));
                          all_rule.push(JSON.parse(stdout))
                          if (files.length - 1 == index) {
                            console
                            elastic().then(() => {
                              resolve('true')
                            })
                          }
                        });
                      })
                    }
                  })

                } catch (err) {
                  console.log(err);
                  return reject('false');
                }
              }
              main()

            });
            file.on('error', function (err) {
              console.error(err);
            });
          } else {
            return reject('false');
          }
        });

      } catch (error) {
        console.log(error);
        return error
      }
    }
  );

این هم خروجی سمت سرور بعد از import کردن یک فایل است که طبق کد لاگ های گرفته شده می آید تا با خطا زیر روبرو میشود.

import_rules
ok ta inaja
Readable {
  _readableState:
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     paused: true,
     emitClose: true,
     autoDestroy: false,
     destroyed: false,
     defaultEncoding: 'utf8',
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  _data:
   <Buffer 50 4b 03 04 0a 00 00 00 00 00 6d 43 a6 46 00 00 00 00 00 00 00 00 00 00 00 00 0f 00 10 00 63 6f 6e 74 65 6e 74 2d 66 69 6c 74 65 72 2f 55 58 0c 00 ae ... >,
  _position: 0,
  _encoding: 'utf8',
  hapi:
   { filename: 'content-filter.zip',
     headers:
      { 'content-disposition': 'form-data; name="file"; filename="content-filter.zip"',
        'content-type': 'application/x-zip-compressed' } } }
end
state Stats {
  dev: 2049,
  mode: 33188,
  nlink: 1,
  uid: 0,
  gid: 0,
  rdev: 0,
  blksize: 4096,
  ino: 1319329,
  size: 123259,
  blocks: 248,
  atimeMs: 1608838510889.3591,
  mtimeMs: 1608838510889.3591,
  ctimeMs: 1608838510889.3591,
  birthtimeMs: 1608838510889.3591,
  atime: 2020-12-24T19:35:10.889Z,
  mtime: 2020-12-24T19:35:10.889Z,
  ctime: 2020-12-24T19:35:10.889Z,
  birthtime: 2020-12-24T19:35:10.889Z }
fileSizeInBytes 123259
fileSizeInMegabytes: 0.123259
exe name content-filter.zip
Extraction complete
{ files: [] }

Current directory filenames:
/usr/share/kibana/node_modules/extract-zip/index.js:46
          cb()
          ^

TypeError: cb is not a function
    at ZipFile.<anonymous> (/usr/share/kibana/node_modules/extract-zip/index.js:46:11)
    at ZipFile.emit (events.js:198:13)
    at FdSlicer.<anonymous> (/usr/share/kibana/node_modules/yauzl/index.js:202:10)
    at Object.onceWrapper (events.js:286:20)
    at FdSlicer.emit (events.js:198:13)
    at onCloseDone (/usr/share/kibana/node_modules/fd-slicer/index.js:74:12)
    at /usr/share/kibana/node_modules/archiver-utils/node_modules/graceful-fs/graceful-fs.js:57:14
    at FSReqWrap.args [as oncomplete] (fs.js:140:20)
 server crashed  with status code 1

ممنون میشم در حل این مشکل بهم کمک کنید!!؟!
@hesammousavi


ثبت پرسش جدید

به همدیگه کمک کنیم

به javad کمک کنید تا مشکل خودش را حل کند؛ این‌طور می‌توانیم با هم پیشرفت کنیم.

برای ارسال پاسخ لازم است وارد شده یا ثبت‌نام کنید

ورود یا ثبت‌نام