Reputation: 89
Hello i just started learning Nodejs and made a local server as a start then i saw that most nodejs apps have config and package files i couldnt find any info on how to do a simple one or use JSON files so i tried myself this is what i got so far
this is the server file
var http = require('http');
var json = require('./package');
var fs = require('fs');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(addr.port);
console.log('server listening at', addr.address + ':' + addr.port);
and this is the json file
{
"addr": {
"address":"http://127.0.0.1",
"port":"8081"
}
}
i know that it will work with json.address and json.port but when i added "addr" i thought it would simplify things with addr.port
so in short an explanation would be generously accepted on why it wont/shouldnt work or what im doing wrong
Upvotes: 0
Views: 113
Reputation: 178
First of you should have a look at some tutorials or introduction sites like:
https://www.w3schools.com/nodejs/default.asp
Second:
The package.json
file is the main configuration file of your nodeJS application. Thats the config file that defines your start point of your application as well as all included modules. simply use npm init
to create a default package.json
file with basic information.
Third:
If you require a json into your application as you did in your example the JSON is included hierarchically. Wich means The object you required has an attribute addr
which itself is a new object with an attribute address
.
So the correct way to access your information is json.addr.address
based on your object description
you could also do something like this:
var network = require('./settings').addr;
console.log("ip => " + network.address);
console.log("port => " + network.port);
Upvotes: 2
Reputation: 493
You need to list the parent object. You have put addr.address and addr.port, this means you are directly trying to access the addr object, but the this object doesn't exist. Try doing json.addr.address and json.addr.port and it should work.
var http = require('http');
var json = require('./package');
var fs = require('fs');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(json.addr.port);
console.log('server listening at', json.addr.address + ':' + json.addr.port);
Upvotes: 1