无法使用stdin读取输入

时间:2017-08-28 04:22:05

标签: node.js

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, {"Content-Type": "text/plain"});
    response.write(JSON.stringify(items));
    response.end();
});
}
http.createServer(onRequest).listen(8000);

返回undefined的项目。有什么建议吗?

提前致谢

2 个答案:

答案 0 :(得分:2)

当您输入字符串stdin时,将\n与字符串一起放在最后。使用以下代码来解决此问题:

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) {
        const opts = {"Content-Type": "text/plain"};
        if(err) {
            console.log(err);
            response.writeHead(404, opts);
            response.write("path not found");
        } else {
            response.writeHead(200, opts);
            response.write(JSON.stringify(items));
        }
        response.end();
    });
}
http.createServer(onRequest).listen(8000);

答案 1 :(得分:1)

不要忘记stdin可能是面向行的(需要一个\n,然后需要剥离)和交互式TTY,但可能不是非互动的,比如我期待@MrTeddy的测试。

编辑:非交互式示例:

const { execFile } = require('child_process');

// Execute the stdin.js test file
const child = execFile('node', ['stdin']);

child.stdout.on('data', (data) => {
    console.log(data);
});

// Send the path
child.stdin.end("./");

stdin.js

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) {
        if (err) return console.log(err);
        response.writeHead(200, {
            "Context-Type": "text/plain"
        });
        response.write(JSON.stringify(items));
        response.end();
    });
}
http.createServer(onRequest).listen(8000);