简体   繁体   English

节点js在嵌套的fs.readFile调用中提供未定义的数据

[英]Node js give undefined data in nested fs.readFile call

This is my first project in nodejs. 这是我在nodejs中的第一个项目。 I am unable to find the cause : 我找不到原因:

在此处输入图片说明

fs.readFile("/home/shaurya/Desktop/test.txt","utf-8", 
 function(err,filedata1){
    fs.readFile(filedata1,"utf-8",function(err,filedata2){
        console.log(filedata1);
        console.log(filedata2);
    });
});

"/home/shaurya/Desktop/test.txt" contains the location of a file as a string. “ /home/shaurya/Desktop/test.txt”以字符串形式包含文件的位置。 I am reading this test.txt in outer readFile call and passing the file content as parameter to inner readFile. 我正在外部readFile调用中读取此test.txt,并将文件内容作为参数传递给内部readFile。

Content of test.txt is : /home/shaurya/Desktop/Parser.hs. test.txt的内容是:/home/shaurya/Desktop/Parser.hs。

I was expecting that I will get the output as a string for console.log(filedata2) call. 我期望我将输出作为console.log(filedata2)调用的字符串。 Instead I got undefined . 相反,我没有undefined

Any thoughts? 有什么想法吗?

在此处输入图片说明

I had a similar problem. 我有一个类似的问题。 In order to solve this you would you would need to append a .trim() method to the filedata1 . 为了解决这个问题,您需要将.trim()方法附加到filedata1 Apparently sometimes text editors put an extra space or new line character after the end of the stream. 显然,有时文本编辑器在流的末尾添加了多余的空格或换行符。 This should solve your problem. 这应该可以解决您的问题。

Your new code: 您的新代码:

fs.readFile("/home/shaurya/Desktop/test.txt","utf-8", 
 function(err,filedata1){
    fs.readFile(filedata1.trim(),"utf-8",function(err,filedata2){
        console.log(filedata1);
        console.log(filedata2);
    });
});

// Please note the .trim() after filedata1 //请注意后.trim() filedata1

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

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