【问题标题】:Get filepath to a variable immedietely after fs.writefile在 fs.writefile 之后立即获取变量的文件路径
【发布时间】:2020-10-09 19:00:45
【问题描述】:

我正在尝试获取我正在编写的文件的路径,如下所示。 帮助我编写如何从以下函数获取路径的代码。

我需要文件路径作为返回变量。我将一个数字作为barcodeSourceNumber 传递。

pathToFile = build_barcode('123456789');

function build_barcode(barcodeSourceNumber) {
 var pngFileName;
  const bwipjs = require('bwip-js');

  bwipjs.toBuffer({
    bcid: 'code128',       // Barcode type
    text: barcodeSourceNumber,    // Text to encode
    scale: 3,               // 3x scaling factor
    height: 10,              // Bar height, in millimeters
    includetext: false,     // Show human-readable text
    textxalign: 'center',   // Always good to set this
  }, function (err, png) {
    var pngFileName = = barcodeSourceNumber + '.png';
    fs.writeFileSync(pngFileName, png);
  });

  return pngFileName;
}

但我得到'。或 undefined 作为我尝试调用该函数时的返回值。

【问题讨论】:

  • 大概,这是因为你试图在这个`return path.dirname(pngFileName);`中引用pngFileName,在bwip-js.toBuffer()完成并在你设置pngFileName的地方调用它的回调。所以,这是一个时间问题。如果bwip-js.toBuffer() 确实是异步的,那么您不能直接返回与其结果相关的任何内容,因为您的函数将在异步回调被调用之前返回。相反,您需要通过回调或承诺将返回值传回。
  • 谢谢,你能给我现有的代码提供一些代码吗,我尝试了很多方法,但它仍然给我'。'
  • 请提供预期的输入和输出。我不清楚您要完成什么。你通过这个函数做什么(给出一个barcodeSourceNumber的具体例子)?您究竟希望该函数返回或与调用者交流什么?为什么最后使用.dirname()?在我看来,您的本地 pngFileName 只是一个没有路径的普通文件名。
  • 你没有回答我的大部分问题。请再次阅读我的评论并回答那里的所有问题。您从一个没有路径的文件名开始,所以path.dirname() 很自然不会给您任何路径。输入'123456789',您期望输出是什么?为什么要在没有路径的文件名上使用path.dirname()?另外,我们需要知道bwipjs.toBuffer() 是同步的还是异步的?它有一个异步的回调,所以这是我的猜测。但是,无论哪种方式,这都会影响您从函数返回数据的方式。
  • 我正在尝试从 fs.writeFileSync(pngFileName, png);作为我在字符串中的输出

标签: javascript node.js file writefile


【解决方案1】:

这就是承诺的作用

function build_barcode(barcodeSourceNumber) {
  var pngFileName;
  const bwipjs = require("bwip-js");

  return new Promise((res, rej) => {
    bwipjs.toBuffer(
      {
        bcid: "code128", // Barcode type
        text: barcodeSourceNumber, // Text to encode
        scale: 3, // 3x scaling factor
        height: 10, // Bar height, in millimeters
        includetext: false, // Show human-readable text
        textxalign: "center", // Always good to set this
      },
      function (err, png) {
        /* error handling  */
        /* if (err) {
          rej(err)
        } */

        var pngFileName = barcodeSourceNumber + ".png";
        fs.writeFileSync(pngFileName, png);
        res(pngFileName);
      }
    );
  });
}

pathToFile = build_barcode("123456789").then((res) => {
  console.log(`pngFileName: ${res}`);
});

【讨论】:

  • 这个没有给我 fs.writeFileSync(pngFileName, png); 新创建的文件路径
【解决方案2】:

当然我不确定 bwipJs.toBuffer 是否是异步的。也可以试试以下方法


pathToFile = build_barcode("123456789");

function build_barcode(barcodeSourceNumber) {
  var pngFileName;
  const bwipjs = require("bwip-js");

  bwipjs.toBuffer(
    {
      bcid: "code128", // Barcode type
      text: barcodeSourceNumber, // Text to encode
      scale: 3, // 3x scaling factor
      height: 10, // Bar height, in millimeters
      includetext: false, // Show human-readable text
      textxalign: "center", // Always good to set this
    },
    function (err, png) {
      pngFileName = barcodeSourceNumber + ".png";
      fs.writeFileSync(pngFileName, png);
    }
  );

  return pngFileName;
}


【讨论】:

    【解决方案3】:

    我建议你这样做:

    const bwipjs = require('bwip-js');
    const fs = require('fs');
    
    async function build_barcode(barcodeSourceNumber) {
        // use promise version of .toBuffer()
        const pngData = await bwipjs.toBuffer({
            bcid: 'code128', // Barcode type
            text: barcodeSourceNumber, // Text to encode
            scale: 3, // 3x scaling factor
            height: 10, // Bar height, in millimeters
            includetext: false, // Show human-readable text
            textxalign: 'center', // Always good to set this
        });
        // combine filename with file extension and turn it into an absolute path
        const pngFileName = path.resolve(barcodeSourceNumber + '.png');
        await fs.promises.writeFile(pngFileName, pngData);
        // make final resolved value be the full filename
        return pngFileName;
    }
    
    build_barcode('123456789').then(result => {
        console.log(result);
    }).catch(err => {
        console.log(err);
    });
    

    变化:

    1. 使用bwipjs.toBuffer() 的promise 版本可以更轻松地返回异步结果
    2. 切换到 fs.promises.writeFile(),因为我们已经在使用 Promise 并且已经是异步的了
    3. require() 移出异步流,因为它是阻塞的
    4. 对函数使用async,这样我们就可以使用await,并且更简单地对多个异步操作进行排序。
    5. 使用 path.resolve() 从我们的文件名中获取完整的绝对路径。
    6. build_barcode() 返回一个承诺,这样我们就可以在几个异步操作结束时更轻松地传回文件名。
    7. 如果调用者只需要与返回的文件名关联的目录名,那么它可以在整个路径名上使用path.dirname() 来获取目录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 2020-06-28
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2017-05-05
      相关资源
      最近更新 更多