如何正确写入.tiff文件至磁盘?写入后无法读取问题排查
写入TIFF文件到磁盘的问题排查与规范
调用接口返回.tiff文件,通过writeFile写入磁盘后文件已创建且大小不为零,但后续无法通过readFile读取解析。以下是代码细节及需要注意的写入规范:
主调用代码
response.on('close', ()=>{ writeToFile("test-4",data,'tiff') .then((msg)=>{ console.log(msg) readFile("test-4.tiff") .then((data)=>{ fromArrayBuffer(data.buffer) .then((geoTIFF)=>{ geoTIFF.getImage() .then((img)=> { console.log(img.fileDirectory.GDAL_METADATA); console.log(img.getWidth(), img.getHeight(), img.getSamplesPerPixel()); }) .catch((e)=>console.log("img.errorMessage:",e)) }) .catch((e)=> console.log("geoTIFF.errorMessage:",e)) }) .catch((e)=> console.log("data.errorMessage:",e)) }) .catch((e)=>{ console.log(msg) }) });
writeToFile 函数
export function writeToFile(path,contents,ext='.tiff') { let newExt = '' return new Promise((resolve,reject)=> { if (typeof (path) !== "string") { reject(new Error("path is not a string.Did you pass string-object using new String(..)")) } if (typeof (ext) !== "string") { reject(new Error("extension is not a string.Did you pass string-object using new String(..)")) } if (contents == undefined) { reject(new Error("contents to be written to the file is undefined")) } if (ext.charAt(0) === '.') { newExt = ext } else { newExt = '.' + ext } fs.writeFile(path+newExt, content,(error)=> { if (error) { reject(new Error("error occured while writing data to file.error:",error," file:",path+newExt)) throw error } resolve("successfully saved the data to file:",path+newExt) }); }) }
readFile 函数
export function readFile(path) { return new Promise((resolve,reject) => { if (typeof (path) !== "string") { console.log("path:",typeof (path)); reject(new Error("path is not a string.Did you pass string-object using new String(..)")) } resolve (fs.readFileSync(path)) }) }
核心问题与写入规范要点
修复变量名拼写错误
writeToFile函数中,参数接收的是contents,但写入时误用了未定义的content变量,这会导致写入无效数据。需将fs.writeFile的第二个参数改为contents。二进制文件的编码设置
TIFF是二进制文件,使用fs.writeFile时必须指定编码为null(或直接传入Buffer类型数据),否则默认以utf8编码处理会破坏二进制结构。修改后的写入代码:fs.writeFile(path+newExt, contents, { encoding: null }, (error)=>{...})流数据的完整收集
接口返回的response是流对象,不应仅在close事件中处理数据。正确做法是在data事件中累加数据,end事件中执行写入,确保数据完整:let chunks = []; response.on('data', (chunk) => chunks.push(chunk)); response.on('end', () => { const data = Buffer.concat(chunks); writeToFile("test-4", data, 'tiff') // 后续处理逻辑 });确保写入数据的有效性
只有当写入的contents是完整、未被篡改的TIFF二进制Buffer时,后续的readFile和GeoTIFF解析才能正常工作。
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

