2017-08-28 45 views
0
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); 

返回未定义的项目。任何建议为什么?无法使用标准输入读取输入

在此先感谢

+0

使用此代码进行快速测试,项目是不是未定义我(我得到的文件列表如预期)。你可以尝试在'fs.readdir'中记录'err',看看有没有错? – MrTeddy

+0

@MrTeddy为什么不给我们测试和/或把它作为答案? –

+0

另外,'http'真的只是读'stdin'的方法吗?我可能会对你想如何实际与这部分软件进行交互感到困惑。 –

回答

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); 
+0

Error:ENOENT:no such file or directory,scandir'C:\ Users \ Narendranath \ Desktop \ Ass-Node at Error(native) errno:-4058, code:'ENOENT', syscall: 'scandir', path:'C:\\ Users \\ Narendranath \\ Desktop \\ Ass-Node \ r'} –

+0

检查编辑@AKSHARAT –

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); 
+1

是的,我也使用了非交互式的。我不确定OP如何互动,也没有想到这一点。作为参考,这是测试https://pastebin.com/eY2mWtau – MrTeddy

+0

请编辑我的答案,添加您的测试文字。让我们不要让人跟随其他网站的链接,可能会删除您的工作! –