为什么要使用writeStream在nodejs中编写比原始文件大的文件?

时间:2019-01-18 10:01:10

标签: javascript node.js file stream

我正在尝试将文件写入json请求有效载荷中以base64字符串形式出现的磁盘。我尝试了writeFile和writeStream,并且没有错误,但是当我尝试将保存的文件作为可执行文件(deb / exe)运行时-它显示错误(tar.gz文件上的某些二进制数据,并且没有要显示的file_to_app结果在deb文件上)。我可以看到通过nodejs保存在磁盘上的文件比原始文件大10到30个字节。是什么导致此问题?

const createProductLink = async (app, product) => {
  try {
    const err = new Error();
    let filename = null;
    let correctTypeFlag = null;
    let temp = null;
    let extData = null;
    let appFormat = null;
    let pathPrefix = null;
    let appType = null;
    if (app.data) {
      [extData] = app.data.split(';');
      [temp, appType] = extData.split(':');
      [temp, appFormat] = appType.split('/');
      const extension = getExtension(appFormat);
      const platform = app.platform.split(' ')[0].toLowerCase();
      console.log(appType, appFormat, extension);
      pathPrefix = getPathPrefix(platform);
      correctTypeFlag = appTypes.includes(extension);
      if (!correctTypeFlag) {
        err.name = 'Validation Error';
        err.message = 'Wrong file format';
        throw err;
      }

  const file = Buffer.from(app.data, 'base64');
  if (file.byteLength > 1024 * 1024 * 300) {
    err.name = 'Validation Error';
    err.message = 'Application size should be less than or equal to 300 MB.';
    throw err;
  }
  filename = `${product.replace(/\s/g, '')}-${app.version}_${app.releaseDate}.${extension}`;
}

return new Promise(async (resolve, reject) => {
  const dest = `${appPathPrefix}${pathPrefix}${filename}`;
  const wStream = fs.createWriteStream(path.join(__dirname, dest));
  await wStream.write(file);
  wStream.on('finish', (error) => {
    if (error) throw error;
    app.link = dest;
    resolve(app.link);
  });
  wStream.on('error', (error) => { console.log('error ', error); reject(error); });
  wStream.on('close', () => console.log('closed'));
  wStream.end();
  resolve(dest);
}).catch(error => { throw error; });
  } catch (err) {
    throw err;
  }
};

0 个答案:

没有答案