Example node.js ftp server? - javascript

I need to create a node.js app that connects to this ftp server and downloads files from this directory:
ftp://www.ngs.noaa.gov/cors/rinex/2021/143/nynb
I've tried following the ftp npm package docs but I feel like I am doing something horribly wrong:
import Client from "ftp";
/**
* https://github.com/mscdex/node-ftp
*/
const c = new Client();
c.on("ready", function () {
c.get(
"ftp://www.ngs.noaa.gov/cors/rinex/2021/143/nynb",
(error, stream) => {
if (error) throw error;
console.log(`stream`, stream);
stream.once("close", function () {
c.end();
});
}
);
});
// connect to localhost:21 as anonymous
c.connect();
When I run npm run dev with nodemon I get:
Error: connect ECONNREFUSED 127.0.0.1:21
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
[nodemon] app crashed - waiting for file changes before starting...
Can someone please help? I'm completely stumped.
Is it possible if someone could show me a small example of how I can connect to this remote ftp server?

There are a few points :
You're connecting to the local ftp with c.connect();. You need to connect to www.ngs.noaa.gov to download files from there.
This path cors/rinex/2021/143/nynb is a directory on the remote host. c.get doesn't work, you need to list all files in the directory then download them 1 by 1.
The code below connect to the remote server and list all files in the directory
const Client = require('ftp');
const fs = require("fs");
const c = new Client();
c.on('ready', function () {
c.list( "/cors/rinex/2021/143/nynb", function (err, list) {
if (err) throw err;
console.dir(list);
});
});
c.connect({
host: "www.ngs.noaa.gov",
});

Related

run child_process to run server.js file

I'm getting a bit lost in child_process docs. What is the recommended way to run a server.js in a child_process ?
Should I run this below? Also, if I kill the main file, will it kill the child process too?
const { exec } = require('child_process')
exec('node server.js')
Backstory: I'm trying to run webpack, but spin up the proxy api server from the webpack JS file.
So after some finicking around here is what I got to run the webpack server and express server at the same time from the same file (NOTE: they do both get killed simultanously :) )
In webpackDevServer.js
child_process.exec('node servers/devServer.js ' + API_SERVER_PORT, (err, stdout, stderr) => {
if (err) {
throw new Error('Proxy server failed to run.', err);
}
})
console.info('> API SERVER: running on port', API_SERVER_PORT)

GRPC client Error: 14 UNAVAILABLE: failed to connect to all addresses

Im trying to test my grpc client connection using below code.
I have .net core grpc server and using node js grpc client to connect. But getting "failed to connect to all addresses" error. BUt able to connect .net grpc server to .net grpc client. Any help much appreciated.
Not sure if im missing anything from below grpc client code.
'use strict';
//Same as the other projects we import fs for reading documents, in this case employees.js json
const fs = require('fs');
//Importing GRPC and the proto loader
const grpc = require('grpc');
const loader = require('#grpc/proto-loader');
//reads the proto
const packageDefinition = loader.loadSync('Repository.proto', {
keepCase: false,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
//Loads the proto file to be used in constant pkg
const pkg = grpc.loadPackageDefinition(packageDefinition);
//Creates server
const PORT = 5001;
//console.log(pkg);
const client = new pkg.repository.Repository('localhost:5001', grpc.credentials.createInsecure());
client.GetUpdates({}, function (err, response) {
console.log("----Response error----");
if (err) {
console.log(err);
} else {
console.log(response);
}
});
im getting below error:
{ Error: 14 UNAVAILABLE: failed to connect to all addresses
at Object.exports.createStatusError (/mnt/c/Users/ht9638/Desktop/workspace/current-workspace/gRPCNodeJS/firstService/node_modules/grpc/src/common.js:91:15)
at Object.onReceiveStatus (/mnt/c/Users/ht9638/Desktop/workspace/current-workspace/gRPCNodeJS/firstService/node_modules/grpc/src/client_interceptors.js:1209:28)
at InterceptingListener._callNext (/mnt/c/Users/ht9638/Desktop/workspace/current-workspace/gRPCNodeJS/firstService/node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus (/mnt/c/Users/ht9638/Desktop/workspace/current-workspace/gRPCNodeJS/firstService/node_modules/grpc/src/client_interceptors.js:618:8)
at callback (/mnt/c/Users/ht9638/Desktop/workspace/current-workspace/gRPCNodeJS/firstService/node_modules/grpc/src/client_interceptors.js:847:24)
code: 14,
metadata: Metadata { _internal_repr: {}, flags: 0 },
details: 'failed to connect to all addresses' }
Can someone please help me on this issue.
I have the same issue when I tried to follow gRPC nodejs tutorials from the official documentation
Root cause(for me): port 50051 are the default port used from the main documentation, when i check the list of the port being used on my laptop, turn out that port 50051 used by "NVIDIA Web Helper.exe".
How i find this out: I tried to change the port slightly to 50052 and console.log the err and it shows as expected

How to deploy React application that makes server calls through Node/Express to IIS?

I have a React application that makes calls to a server.js file - these calls are requests to get data from a database with the use of queries (I'm using MSSQL).
Here is my server.js:
var express = require('express');
var app = express();
var sql = require("mssql");
var cors = require('cors');
app.use(cors())
var database =    {
    server: xxx,
    authentication: {
        type: 'default',
        options: {
            userName: ‘xxx’,
            password: ‘xxx’,
        },
    },
    options: {
        database: ‘xxx’,
        encrypt: false,
    },
}
app.get(‘/gettingInfo’, function(req, res)    {
    sql.connect(database, function(err)  {
        if (err)    {
            console.log("ERROR HERE")
            console.log(err);
        }
        var request = new sql.Request();  
const finalRoomQuery = [query];
        request.query(finalRoomQuery, function(err, recordset)  {
            if (err)    {
                console.log(err);
            }
            res.send(recordset);
        });
    });
});
var server = app.listen(5000, function ()   {
    console.log('Server is running...');
});
Below is sample bit of code from one of my components that retrieves data from my server.js:
getData = () => {
if (this.mounted === true) {
fetch('http://localhost:5000/gettingInfo')
.then(results => results.json())
.then(results => this.setState({data: results}))
.catch(err => console.error(err));
}
}
When I run node server.js in my project directory, followed my npm start, my react application is able to retrieve data and render it appropriately.
I'm working on deploying my application. I ran npm run build to build the application, and I've deployed it to IIS. This is where I'm running into problems - if I don't have localhost:5000 running on my machine (i.e if node server.js is not entered), my application cannot query for the data needed, I get a (failed) net::ERR_CONNECTION_REFUSED. However, when I have localhost:5000 running, the application on IIS will run as expected.
My question is: how can I host this server.js file as well, and/or how can I configure this project so that I don't have to have localhost:5000 running for the application to work properly? I apologize if this is some straight forward fix or if I'm missing something very basic, this is my first experience with Web Dev.
In your server code, you are not sending response back in all cases.
app.get(‘/gettingInfo’, function(req, res) {
sql.connect(database, function(err) {
if (err) {
console.log("ERROR HERE")
console.log(err);
return res.send("Error Message");
}
var request = new sql.Request();
const finalRoomQuery = [query];
request.query(finalRoomQuery, function(err, recordset) {
if (err) {
console.log(err);
return res.send("Error Message");
}
return res.send(recordset);
});
});
});
You need to use process managers like PM2 and run your server in that console.
pm2

Can't start MongoDB on localhost for node.js

I am a beginner to node.js and MongoDB. I am trying to setup a basic project like so.
In my project dir I run node init, accept the default values and then run npm install --save mongodb. In my index.js I have the following code:
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:3333/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Now when I run node index.js I get the following error:
failed to connect to server [localhost:3333] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:3333]
I have tried changing the port number but still get the same error. What am I doing wrong here?
By default the MongoDB server is running on port 27017. You need to change the connection string to mongodb://localhost:27017/mydb.
First you need to install MongoDB if you don't already have it installed. Visit MongoDB site to download.
Follow the instructions there on how to start it up and running, after that try running your app again.
Also by default MongoDB runs on port 27017 so your url should point to localhost:27017.
// Import the mongodb module
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});

node.js Error: connect ECONNREFUSED; response from server

I have a problem with this little program:
var http = require("http");
var request = http.request({
hostname: "localhost",
port: 8000,
path: "/",
method: "GET"
}, function(response) {
var statusCode = response.statusCode;
var headers = response.headers;
var statusLine = "HTTP/" + response.httpVersion + " " +statusCode + " " + http.STATUS_CODES[statusCode];
console.log(statusLine);
for (header in headers) {
console.log(header + ": " + headers[header]);
}
console.log();
response.setEncoding("utf8");
response.on("data", function(data) {
process.stdout.write(data);
});
response.on("end", function() {
console.log();
});
});
The result in console is this:
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:8000
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
I do not understand why this happens.
From your code, It looks like your file contains code that makes get request to localhost (127.0.0.1:8000).
The problem might be you have not created server on your local machine which listens to port 8000.
For that you have to set up server on localhost which can serve your request.
Create server.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!'); // This will serve your request to '/'.
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!');
});
Run server.js : node server.js
Run file that contains code to make request.
Please use [::1] instead of localhost, and make sure that the port is correct, and put the port inside the link.
const request = require('request');
let json = {
"id": id,
"filename": filename
};
let options = {
uri: "http://[::1]:8000" + constants.PATH_TO_API,
// port:443,
method: 'POST',
json: json
};
request(options, function (error, response, body) {
if (error) {
console.error("httpRequests : error " + error);
}
if (response) {
let statusCode = response.status_code;
if (callback) {
callback(body);
}
}
});
I solved this problem with redis-server, you can install that like this!
sudo apt-get install redis-server
after that see the port and change it!
I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...
Just run the following command in the node project:
npm install
Its worked for me.
i ran the local mysql database, but not in administrator mode, which threw this error
If you have stopped the mongod.exe service from the task manager, you need to restart the service. In my case I stopped the service from task manager and on restart it doesn't automatically started.
I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.
If this is the problem with connecting to the redis server (if your redis.createClient function does not work although you are sure that you have written the right parameters to the related function), just simply type redis-server in another terminal screen. This probably gonna fix the issue.
P.S.: Sorry if this is a duplicate answer but there is no accepted answer, so, I wanted to share my solution too.
This is very slight error. When I was implementing Event server between my processes on nodejs.
Just check for the package you're using to run your server like Axios.
Maybe you might have relocated the files or disconnected some cache data on the browsers.
It's simple ,In your relevant directory run the following command
I was using axios so I used
npm i axios
Restart the server
npm start
This will work.
use a proxy property in your code it should work just fine
const https = require('https');
const request = require('request');
request({
'url':'https://teamtreehouse.com/chalkers.json',
'proxy':'http://xx.xxx.xxx.xx'
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = body;
console.log(data);
}
}
);

Categories