问题描述
我正在尝试获取要写入的文件的路径,如下所示。 用代码帮助我如何从下面的函数获取路径。
我需要文件路径作为返回变量。我正在传递一个数字作为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;
}
解决方法
这就是诺言
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}`);
});
,
当然,我不确定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,in millimeters
includetext: false,// Show human-readable text
textxalign: "center",// Always good to set this
},png) {
pngFileName = barcodeSourceNumber + ".png";
fs.writeFileSync(pngFileName,png);
}
);
return pngFileName;
}
,
这是我建议您做的事情:
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',// 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);
});
更改:
- 使用
bwipjs.toBuffer()
的Promise版本可以简化回传异步结果的操作 - 切换到
fs.promises.writeFile()
,因为我们已经在使用promises并且已经异步 - 将
require()
从异步流中移出,因为它会阻塞 - 对该函数使用
async
,以便我们可以使用await
并更简单地对多个异步操作进行排序。 - 使用
path.resolve()
从文件名获取完整的绝对路径。 - 使
build_barcode()
返回一个保证,以便我们可以在几个异步操作结束时更轻松地传回文件名。 - 如果调用方只想要与返回的文件名关联的目录名,则可以在整个路径名上使用
path.dirname()
来获取目录。