简体   繁体   English

在NodeJS处传递的图像文件参数

[英]Image file parameter passing at NodeJS

I have a method from where I pass a text and image file as a parameter to another function. 我有一个方法,从这里我将文本和图像文件作为参数传递给另一个函数。 The text is passed but the image file is always undefined. 传递了文本,但是图像文件始终未定义。 What am I missing? 我想念什么?

    function anotherFunc(text, imageFile){

      if (typeof imageFile == 'undefined'){
        console.log("image undefined")
      } else {
        console.log("Got image")
    }
 }

function theCaller(){
  var text ="hello"
  var imageFile = 'img.png'
  anotherFunc(text, imageFile)
}

This always outputs image undefined although I have the image in the same directory of the source code. 尽管我将图像放在源代码的同一目录中,但始终会输出undefined的图像。 I have also tried var imageFile = './img.png' but that does not help either. 我也尝试过var imageFile = './img.png'但这也无济于事。

if you'd like to test imageFile whether it's undefined or not you should do it like: 如果要测试imageFile是否未定义,则应执行以下操作:

if (typeof imageFile == 'undefined'){
   console.log("image undefined")
  } else {
    console.log("Got image")
  }

You are only verifying that the string is not "undefined". 您仅在验证字符串不是“未定义”。 Besides changing the code to correctly verify if it is undefined by either saying if (imageFile) or more explicitly if (typeof imageFile === 'undefined') you also need to actually provide an image and not just the text. 除了更改代码以通过说if (imageFile)或更明确的if (typeof imageFile === 'undefined')来正确验证其是否未定义外,您还需要实际提供一个图像,而不仅仅是文本。

I would suggest you to do something like this: 我建议您做这样的事情:

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

let fileName = 'someName.png';
let fullPath = path.join(__dirname, 'some', 'path', fileName);

if (fs.existsSync(fullPath)) {
  let file = fs.readFileSync(fullPath);
  // do something with the file
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM