I've started the tutorial for Node.JS on tutorialspoint, but I can't get past the first step: https://www.tutorialspoint.com/nodejs/nodejs_first_application.htm
I us MacOS 10.13.5
I've created the following js file, named main.js.
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
It's a copy-paste of the tutorial, but when I try to run the given command node main.js nothing happens.
When I write the code directly in the node CLI I get the following response:
Server {
domain:
Domain {
domain: null,
_events: { error: [Function: debugDomainError] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events:
{ request: [Function],
connection: [Function: connectionListener] },
_eventsCount: 2,
_maxListeners: undefined,
_connections: 0,
_handle:
TCP {
reading: false,
owner: [Circular],
onread: null,
onconnection: [Function: onconnection],
writeQueueSize: 0 },
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::8081',
[Symbol(asyncId)]: 192 }
Edit:
The first time I tried writing it in the command line I misspelled response. I fixed it now and now I get the above response.
Edit 2
Here's what happens in the terminal. I included ls so you can see that it contains the file I'm trying to call
After running ps -a | grep node I saw I already had a process running. After I killed it I was able to execute my file.
Related
Okay, so I have what is effectively two identical (to my eyes at least!) pieces of Node JS code. The only difference is that in once case it is wrapped up in a function and called via that function and in the other case, the code sits outside any function. When I run the two pieces, of what should be identical code, I get vastly different results. Why is this?
Here is the code when not inside of a function:
chunks = []
req = https.get('https://www.example.com',
res => {
res.setEncoding('utf8')
res.on('data', chunk => {
chunks.push(chunk)
})
res.on('end', function(){
chunks.join()
})
}).end()
console.log(chunks[0])
Here is me using what, as far as I can tell, should effectively be the exact same code but via a function format:
function readURI(uri){
const chunks = []
const req = https.get(uri, res => {
res.setEncoding('utf8')
res.on('data', chunk => {
chunks.push(chunk)
})
res.on('end', function(){
chunks.join()
})
})
req.end()
return chunks[0]
}
console.log(readURI('https://www.example.com'))
I run both of these in the Node REPL. In the first instance, chunks[0] is a string with the content of the website as I expect. In the second, I get no data in the return of the function. Why would this happen?
There are two things at play here.
When a line is evaluated, the completion value of the line is displayed when using the Node REPL - even if the line doesn't include a console.log. As a result, the first code's req = https.get('https://www.example.com', logs the request object.
Look at what gets logged carefully - it really does not contain the content of the website anywhere - the request is asynchronous, it has not finished by the time the final line is executed.
Welcome to Node.js v14.17.6.
Type ".help" for more information.
> const https = require('https');
undefined
> chunks = []
[]
> req = https.get('https://www.example.com',
... res => {
..... res.setEncoding('utf8')
..... res.on('data', chunk => {
....... chunks.push(chunk)
....... })
..... res.on('end', function(){
....... chunks.join()
....... })
..... }).end()
ClientRequest {
_events: [Object: null prototype] {
response: [Function: bound onceWrapper] { listener: [Function (anonymous)] }
},
_eventsCount: 1,
_maxListeners: undefined,
outputData: [
{
data: 'GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n',
encoding: 'latin1',
callback: [Function: bound onFinish]
}
],
outputSize: 60,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: null,
_header: 'GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: noopPendingOutput],
agent: Agent {
_events: [Object: null prototype] {
free: [Function (anonymous)],
newListener: [Function: maybeEnableKeylog]
},
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
>
options: { path: null },
requests: {},
sockets: { 'www.example.com:443:::::::::::::::::::::': [Array] },
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 1,
maxCachedSessions: 100,
_sessionCache: { map: {}, list: [] },
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/',
_ended: false,
res: null,
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'www.example.com',
protocol: 'https:',
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] { host: [ 'Host', 'www.example.com' ] }
}
> console.log(chunks[0])
undefined
undefined
>
The website content is not in there - in either version of your code, as expected. It's just that your first code has the request as a completion value of a line, but the second code does not - and in the function version, chunks is an empty array when readURI finishes, so undefined is returned.
Unless you're sure you know exactly how the REPL works, to avoid confusing yourself, I'd recommend running scripts as their own files - eg node example.js - for anything that isn't exceedingly trivial.
This was a simple mistake in interacting with the REPL. In entering the code into the REPL, I did so without a new line on the last line of code and so the request object has been made and completed by the time I hit enter on the final console.log line. In the case of the function based snippet, this doesn't matter as the request is made in the same line and doesn't have time to complete by the time the log is made.
I'm new to skill dev and am trying to make an API call from within an intent (for the sake of this example, I am just using Google). For whatever reason, the log statements never execute in my HTTP request:
var test = http.get('http://www.google.com', function (result) {
console.log('Success, with: ' + result.statusCode);
}).on('error', function (err) {
console.log('Error, with: ' + err.message);
});
console.log('test is', test);
The test log statement after the request returns a ClientRequest object. Below is the full log output:
START RequestId: aaa9d350-3c3c-11e7-8840-4bab41953f86 Version: $LATEST
2017-05-19T02:41:32.961Z aaa9d350-3c3c-11e7-8840-4bab41953f86 Warning: Application ID is not set
2017-05-19T02:41:33.139Z aaa9d350-3c3c-11e7-8840-4bab41953f86 test is ClientRequest {
domain: null,
_events:
{ response: { [Function: g] listener: [Function] },
socket: { [Function: g] listener: [Function: onSocket] },
error: [Function] },
_eventsCount: 3,
_maxListeners: undefined,
output: [ 'GET / HTTP/1.1\r
Host: www.google.com\r
Connection: close\r
\r
' ],
outputEncodings: [ 'latin1' ],
outputCallbacks: [ [Function: finish] ],
outputSize: 59,
writable: true,
_last: true,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedHeader: {},
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: null,
connection: null,
_header: 'GET / HTTP/1.1\r
Host: www.google.com\r
Connection: close\r
\r
',
_headers: { host: 'www.google.com' },
_headerNames: { host: 'Host' },
_onPendingData: null,
agent:
Agent {
domain: null,
_events: { free: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 80,
protocol: 'http:',
options: { path: null },
requests: {},
sockets: { 'www.google.com:80:': [Object] },
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256 },
socketPath: undefined,
timeout: undefined,
method: 'GET',
path: '/',
_ended: false }
END RequestId: aaa9d350-3c3c-11e7-8840-4bab41953f86
REPORT RequestId: aaa9d350-3c3c-11e7-8840-4bab41953f86 Duration: 338.91 ms Billed Duration: 400 ms Memory Size: 128 MB Max Memory Used: 46 MB
I thought it must be related to it being an async function, but I haven't had any luck.
Is it possibly a setting in AWS Lambda that I need to configure?
I am following this tutorial from ArangoDB.com.
It is about creating Arango database using node.js. I am doing it on OS X.
After executing in node code:
> Database = require('arangojs').Database;
[Function: Database]
> db = new Database('http://127.0.0.1:8529');
Database {
_connection:
Connection {
config:
{ url: 'http://127.0.0.1:8529',
databaseName: '_system',
arangoVersion: 20300,
agentOptions: [Object],
headers: [Object] },
_request: [Function: request],
promisify: [Function] },
_api:
Route {
_connection:
Connection {
config: [Object],
_request: [Function: request],
promisify: [Function] },
_path: '_api',
_headers: undefined },
name: '_system' }
> db.createDatabase('mydb', function (err) {
if (!err) console.log('Database created');
else console.error('Failed to create database:', err);
});
I am getting ECONNREFUSED error:
Failed to create database: { [Error: connect ECONNREFUSED 127.0.0.1:8529]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8529,
request:
ClientRequest {
domain:
Domain {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events: { response: [Object], error: [Function] },
_eventsCount: 2,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedHeader: { 'content-length': false },
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket:
Socket {
_connecting: false,
_hadError: false,
_handle: null,
_parent: null,
_host: null,
_readableState: [Object],
readable: false,
domain: [Object],
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: false,
allowHalfOpen: false,
destroyed: true,
bytesRead: 0,
_bytesDispatched: 0,
_sockname: null,
_pendingData: [Object],
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Circular],
read: [Function],
_consuming: true,
_idleNext: null,
_idlePrev: null,
_idleTimeout: -1 },
connection:
Socket {
_connecting: false,
_hadError: false,
_handle: null,
_parent: null,
_host: null,
_readableState: [Object],
readable: false,
domain: [Object],
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: false,
allowHalfOpen: false,
destroyed: true,
bytesRead: 0,
_bytesDispatched: 0,
_sockname: null,
_pendingData: [Object],
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Circular],
read: [Function],
_consuming: true,
_idleNext: null,
_idlePrev: null,
_idleTimeout: -1 },
_header: 'POST /_db/_system/_api/database HTTP/1.1\r\ncontent-type: application/json\r\ncontent-length: 15\r\nx-arango-version: 20300\r\nHost: 127.0.0.1:8529\r\nConnection: keep-alive\r\n\r\n',
_headers:
{ 'content-type': 'application/json',
'content-length': 15,
'x-arango-version': 20300,
host: '127.0.0.1:8529' },
_headerNames:
{ 'content-type': 'content-type',
'content-length': 'content-length',
'x-arango-version': 'x-arango-version',
host: 'Host' },
_onPendingData: null,
agent:
Agent {
domain: [Object],
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 80,
protocol: 'http:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: true,
maxSockets: 3,
maxFreeSockets: 256 },
socketPath: undefined,
method: 'POST',
path: '/_db/_system/_api/database',
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': null,
_headers: [],
_url: '',
_consumed: false,
socket: [Object],
incoming: null,
outgoing: [Circular],
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncomingClient] } } }
Unfortunately I can't localise error. I was searching for similar porblems but didn't find any solutions. I don't have much experience with these technologies and I am just starting ArangoDB now.
I would be grateful for any tips how to solve it and/or any other materials how to start with ArangoDB.
The error indicates that the client could not connect, presumably ArangoDB is not running at port 8529 on localhost, hasn't been started or hasn't finished starting.
The tutorial should work from the node shell but you may have to avoid line breaks (e.g. before a . when calling a method like .then). The code in the examples has been formatted for readability, the screenshots may be safer if you want something to follow along.
In general if you have multiple line of code that you need to run using node it is best to create a JavaScript file that contains all the code you want to run such as script.js. To run that code you use node script.js. This will cause node to evaluate your code line by line and (potentially) persistently keep the code running the code (things like a server would do this).
Using the node shell (aka just running node directly) will not be a good strategy to have persistently running code.
So in conclusion: place any server code in a script.js then run it with the command node script.js inside of a bash shell (where node is installed).
It very likely code not start a server and persistently consume a port while inside the shell.
I have an application that I'm writing using express.js. When I run the application on my laptop, on each request, I see a very large object dumped as JSON to the console. It starts like this and goes on for many lines:
{ domain: null,
_events: null,
_maxListeners: 10,
socket:
{ domain: null,
_events:
{ drain: [Function: ondrain],
timeout: [Object],
error: [Function],
close: [Object] },
_maxListeners: 10,
_handle:
{ writeQueueSize: 0,
owner: [Circular],
onread: [Function: onread] },
_pendingWriteReqs: 0,
_flags: 0,
_connectQueueSize: 0,
destroyed: false,
errorEmitted: false,
bytesRead: 483,
_bytesDispatched: 0,
allowHalfOpen: true,
writable: true,
readable: true,
server:
The odd thing is that the exact same code doesn't do this on my PC. I guess this isn't an error as such but it means I can't see any useful output in the terminal. I'm at a loss as to why I'm getting this output.
I resolved the problem by deleting the node_modules directory in my project and than running npm install to re-download the required modules. Clearly something wasn't right in one of the modules.
I'm using node.js and express to create a controller of sorts for my home media centre that can be operated through a browser.
I'm having a lot of trouble spawning the VLC process, but strangely only it works when executed from the node prompt, just not when run from file.
Here is what I have tested:
In the node command line/interpreter: require('child_process').spawn('vlc');
This works as I would expect, I can see the vlc window opens and persists on screen.
If I take the exact same line of code and I place it in another file (say test.js) and run that from the command line with node test.js nothing happens. Logging out the child process object a few seconds later gives me this:
{ _closesNeeded: 3,
_closesGot: 3,
signalCode: null,
exitCode: 1,
killed: false,
_internal: null,
pid: 11837,
stdin:
{ _handle: null,
_pendingWriteReqs: 0,
_flags: 0,
_connectQueueSize: 0,
destroyed: true,
bytesRead: 0,
bytesWritten: 0,
allowHalfOpen: undefined,
writable: false,
readable: false,
_connecting: false,
_connectQueue: null,
_idleNext: null,
_idlePrev: null },
stdout:
{ _handle: null,
_pendingWriteReqs: 0,
_flags: 1,
_connectQueueSize: 0,
destroyed: true,
bytesRead: 0,
bytesWritten: 0,
allowHalfOpen: undefined,
writable: false,
readable: false,
_events: { close: [Function] },
_connecting: false,
_connectQueue: null,
_idleNext: null,
_idlePrev: null },
stderr:
{ _handle: null,
_pendingWriteReqs: 0,
_flags: 1,
_connectQueueSize: 0,
destroyed: true,
bytesRead: 215,
bytesWritten: 0,
allowHalfOpen: undefined,
writable: false,
readable: false,
_events: { close: [Function] },
_connecting: false,
_connectQueue: null,
_idleNext: null,
_idlePrev: null } }
What is particularly weird about this is that I can launch other programs in the same way and it works. For instance replacing 'vlc' with 'gedit' results in the text editor appearing exactly as expected.
Anyone got ideas as to what this could be?
This is just a hunch, but I bet you are prematurely exiting your test before the VLC process even gets "running" so to speak.
Execute it like this:
var spawn = require('child_process').spawn;
var vlc = spawn('vlc');
vlc.on('exit', function(code){
console.log('Exit code: ' + code);
//EXIT TEST HERE
});
Spawn Documentation.
Edit:
Just saw 'test.js' and thought you were running a test. Post the relevant part of your Express code.