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);
आइटम अपरिभाषित लौट रहे हैं। कोई सुझाव क्यों?
अग्रिम में धन्यवाद
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);
यह भी न भूलें कि stdin
एक इंटरएक्टिव TTY के साथ लाइन-ओरिएंटेड (अंत में एक \n
की आवश्यकता होगी जिसे बाद में अलग करने की आवश्यकता होगी), लेकिन एक गैर-इंटरैक्टिव के साथ नहीं हो सकता है परीक्षण के रूप में मुझे उम्मीद है कि @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);
नए सवाल
node.js
Node.js एक घटना-आधारित, गैर-अवरोधक, अतुल्यकालिक I / O रनटाइम है जो Google के V8 जावास्क्रिप्ट इंजन और libuv लाइब्रेरी का उपयोग करता है। इसका उपयोग उन अनुप्रयोगों को विकसित करने के लिए किया जाता है जो क्लाइंट पर और साथ ही सर्वर साइड पर जावास्क्रिप्ट को चलाने की क्षमता का भारी उपयोग करते हैं और इसलिए कोड के पुन: प्रयोज्य और संदर्भ स्विचिंग की कमी से लाभान्वित होते हैं।