AKSHARA T AKSHARA T - 2 months ago 13
Node.js Question

Unable to read input using stdin

var http = require('http');
var fs = require('fs');
var path="";
process.stdin.on('data', function(chunk) {
var buffer = new Buffer(chunk);
path = buffer.toString();
});
function onRequest(request, response) {
console.log("Request received" + path);
fs.readdir(path, function(err, items) {
response.writeHead(200, {"Context-Type": "text/plain"});
response.write(JSON.stringify(items));
response.end();
});
}
http.createServer(onRequest).listen(8000);


items returning undefined. Any suggestions Why ??

Thanks in advance

Answer Source

When you enter a string stdin puts \n at the end along with the string.Use the following code to solve this:

var http = require('http');
var fs = require('fs');
var path="";
process.stdin.on('data', function(chunk) {      
    var buffer = new Buffer(chunk);
    path = buffer.toString();    
    path = path.replace("\n","");
    path = path.replace("\r","");
});
function onRequest(request, response) {
    console.log("Request received" , path);    
    fs.readdir(path, function(err, items) {
        if(err) {
            console.log(err);
            response.writeHead(200, {"Context-Type": "text/plain"});
            response.write("path not found");
            response.end();
        } else {
            response.writeHead(200, {"Context-Type": "text/plain"});
            response.write(JSON.stringify(items));
            response.end();
        }
    });
}
http.createServer(onRequest).listen(8000);