简体   繁体   English

根据Node.js中的Key返回值

[英]Return Value based on Key in Node.js

I'm quite new to the world of JS and Node so this might seem like quite an easy thing to do, but it's something I just can't seem to get working. 我对JS和Node还是很陌生,所以这似乎很容易做到,但是我似乎无法正常工作。

Say I have the following json example in a json file 说我在json文件中有以下json示例

{
"0": "somestring1",
"1": "somestring2",
"2": "somestring3",
"3": "somestring4",
"4": "somestring5",
"5": "somestring6",
"6": "somestring7"
}

and in my server.js file I am loading the file like so 在我的server.js文件中,我像这样加载文件

var fs = require('fs')

var parsedJson = fs.readFile('./jsonfile.json', function (err, data) 
{
  res.write(data);
  res.end();
})

hitting the server returns all of the json (as expected) but what I want to do is parse the file and return a single value based on a key, so something along the lines of: 击中服务器将返回所有json(如预期的那样),但我要执行的操作是解析文件并基于键返回单个值,因此可以实现以下目的:

for (var entry in data)
{
    if (entry.key == 0)
    {
      res.write(thing.value);
      //"somestring1" would be sent here
    }
}

How is this sort of thing done in JS/Node. 这种事情如何在JS / Node中完成。 Everything I have tried doesn't seem to work 我尝试过的一切似乎都没有用

Thanks! 谢谢!

Kris 克里斯

Maybe something like this? 也许是这样的吗?

var http = require('http');
var fs = require('fs');

var data = JSON.parse(fs.readFileSync('data.json'));

var server = http.createServer(function(req, res) {
  var key = req.url.replace('/', '');
  var value = data[key];

  if (value) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(value);
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Not Found');
  }
});

server.listen(1337, '127.0.0.1');

Then on the command line: 然后在命令行上:

$ curl localhost:1337/1
somestring2

$ curl localhost:1337/x
Not Found

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM