简体   繁体   English

如何将字符串传递给 fs.readFileSync

[英]How to pass String in to fs.readFileSync

I'm trying to convert string in to Buffer using readFileSync .It's return buffer with hard coded string.but not when i pas string.我正在尝试使用readFileSync将字符串转换为缓冲区。它是带有硬编码字符串的返回缓冲区。但当我传递字符串时不是。

----working --- - - 在职的 - -

const buffer = fs.readFileSync('./test/JFwZCrdEojAr09ajT8EPZmo.jpg',{ encoding: 'utf8' });

----not working --- ----不工作---

var pathString = './test/JFwZCrdEojAr09ajT8EPZmo.jpg';
const buffer = fs.readFileSync(pathString,{ encoding: 'utf8' });

i'm getting bellow error我收到以下错误

Error: ENOENT: no such file or directory, open './test/JFwZCrdEojAr09ajT8EPZmo.jpg'错误:ENOENT:没有这样的文件或目录,打开“./test/JFwZCrdEojAr09ajT8EPZmo.jpg”

Both ways working fine in local machine.but when deploy in to server,above happening.这两种方式在本地机器上都运行良好。但是当部署到服务器时,上述情况发生了。

Both should be work.两者都应该工作。 check your image file still exists.检查您的图像文件是否仍然存在。

This is not answer and will be deleted or transformed to the answer depending on the results. 这不是答案,将根据结果删除或转换为答案。

@Yasiry, could you please run this code on you machine and post the output? @Yasiry,能否请您在计算机上运行此代码并发布输出?

const fs = require('fs');

try {
    fs.readFileSync('./test/JFwZCrdEojAr09ajT8EPZmo.jpg', { encoding: 'utf8' });
    console.log('file using STRING found');
} catch (e) { console.log('file using STRING NOT found'); }

try {
    const pathString = './test/JFwZCrdEojAr09ajT8EPZmo.jpg';
    fs.readFileSync(pathString, { encoding: 'utf8' });
    console.log('file using VARIABLE found');
} catch (e) { console.log('file using VARIABLE NOT found'); }

I assume, both will fail or success. 我想,两者都会失败或成功。 In this case you need to check other parts of your code. 在这种情况下,您需要检查代码的其他部分。

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

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