2017-08-28 75 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

請編輯我的答案,添加您的測試文字。讓我們不要讓人跟隨其他網站的鏈接,可能會刪除您的工作! –