Address Info Syntax Error Node.js (Express) - javascript

I am making a server using TypeScript that my angular app can connect to, but I get the following error when I try to run it: (PS I tried using destructuring with the AddressInfo, but Node.js or TS is not compatible yet with ES6 features)
const {address, port} = server.address() as AddressInfo;
^^
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:720:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:643:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:839:10)
at internal/main/run_main_module.js:17:11
The code below:
const express = require('express');
const AddressInfo = require('AddressInfo');
const app = express();
app.get('/', (req, res) => res.send('Hello from Express'));
app.get('/products', (req, res) => res.send('Got a request for products'));
app.get('/reviews', (req, res) => res.send('Got a request for reviews'));
const server = app.listen(8000, "localhost", () => {
const {address, port} = server.address() as AddressInfo;
console.log(`Listening on ${address}:${port}`);
});

The as key word is not vanilla JavaScript, it is TypeScript,also Node.js runs JavaScript, if you need to use TypeScript you can use the the node Typescript package it allows you to transpile .ts files into .js or use babel

I am making a server using TypeScript
More accurately, you are making a server using NodeJS. Node only natively supports JavaScript. The quick fix here is to remove as AddressInfo since this is TypeScript syntax, not JavaScript.
If you really want to use TypeScript instead of JavaScript, you need to rename your .js files to .ts and configure NodeJS to use TypeScript.

Related

How to use node_modules in Deno as typescript imports?

Project: REST API for serving information stored in a neo4j graph database.
Backend: Deno
I am farely new to deno, but I'm not new to typescript, having used it in Angular frequently.
Problem: I want to use a driver to connect my neo4j database to my backend, but there is no neo4j driver made for Deno. I have scoured the internet and documentation for solutions, and have been trying to import the javascript library using the node modules import tool that has been suggested from similar answers and is supported by the deno team.
Essentially, I do npm install neo4j-driver, and then add the following code to my deno project.
Failed Solution: the javascript node modules wrapper
I implement call this function as a test for my deno server in a server.ts file.
The command I use for deno is: deno run --allow-all --unstable server.ts
neo4j_conn.ts file: (called by server.ts)
import { createRequire } from "https://deno.land/std/node/module.ts";
const require = createRequire(import.meta.url);
export async function testconnection(uri: string, user: string, password: string) {
//This is the line that fails.
var neo4j = require('neo4j-driver').v1; //this fails whether or not I include the .v1 or not.
var driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
const session = driver.session()
const personName = 'Alice'
try {
const result = await session.run(
'CREATE (a:Person {name: $name}) RETURN a',
{ name: personName }
)
const singleRecord = result.records[0]
const node = singleRecord.get(0)
console.log(node.properties.name)
} finally {
await session.close()
}
await driver.close()
}
This returns the following error:
error: Uncaught (in promise) Error: Cannot find module 'net'
Require stack:
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/node/node-channel.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/node/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/bolt/handshake.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/bolt/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver/lib/index.js
- /mnt/c/Users/xxxxx/source/private_logic/deno-try/neo4jconn.ts
at Function._resolveFilename (https://deno.land/std#0.97.0/node/module.ts:273:19)
at Function._load (https://deno.land/std#0.97.0/node/module.ts:380:29)
at Module.require (https://deno.land/std#0.97.0/node/module.ts:133:21)
at require (https://deno.land/std#0.97.0/node/module.ts:1158:16)
at Object.<anonymous> (file:///mnt/c/Users/xxxxx/source/private_logic/deno-try/node_modules/neo4j-driver-bolt-connection/lib/channel/node/node-channel.js:24:29)
at Module._compile (https://deno.land/std#0.97.0/node/module.ts:168:36)
at Object.Module._extensions..js (https://deno.land/std#0.97.0/node/module.ts:1109:10)
at Module.load (https://deno.land/std#0.97.0/node/module.ts:147:34)
at Function._load (https://deno.land/std#0.97.0/node/module.ts:413:14)
at Module.require (https://deno.land/std#0.97.0/node/module.ts:133:21)
As far as I could tell, I had done everything right, but I am a little in over my head when it comes to the typescript/js module translation.
My file structure is as follows:
package.json
package-lock.json
server.ts
neo4j_conn.ts
node_modules -|
|
:
Neo4j developer js docs: https://neo4j.com/developer/javascript/
Deno node modules "require": https://doc.deno.land/https/deno.land/std#0.97.0/node/module.ts
If you look at the Node compatibility layer README in std you will realize that right now there is no compatibility module for the net library. The compatibility will improve day by day, but take into account that Deno is not a drop in replacement for Node, but a whole new thing that won't work with Node libraries by default
https://deno.land/std#0.97.0/node

Node.js async await in express

I'm building an endpoint /users which will return the contents in the Users.json file. I'm using aysnc/await feature.
var express = require('express');
var app = express();
var fs = require('fs');
var readFile = Promise.promisify(fs.readFile);
const util = require('util');
app.get('/users', async (req, res, next) => {
try {
const user = await readFile('./users.json');
return eval(user);
//res.send(JSON.parse(data));
// res.json(user);
} catch (e) {
//this will eventually be handled by your error handling middleware
next(e)
}
});
app.listen(3000,function(){
console.log("listening on port 3000");
});
This throws the below error
SyntaxError: Unexpected token (
at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28) at Object.Module._extensions..js
(module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad
(module.js:446:12) at Function.Module._load (module.js:438:3) at
Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at
startup (bootstrap_node.js:149:9)
I'm using the npm 3.10.10 with node v6.11.3.
Can someone please guide where I have gone wrong?
Async/await is only available in Node versions 8 an up. Try using a newer Node version if possible.
Instead of calling:
return eval(user);
You should call:
res.send(JSON.parse(user));
or
res.send(JSON.stringify(JSON.parse(user)));
and use bodyParser.json() middleware if returning an object.
Likewise in the catch block,
res.status(500).send(‘there was an error’);
and log the error to your console.
——-
Also, fs.readFile takes another param, the encoding. Use ‘utf-8’. It returns a buffer, not a string, if you leave it out.

Nodejs - throw unpredictable error as `property 'get' of undefined`

I am trying to run my node app. But I am getting an error, which I am not able to understand. please any one help me to understand this?
here is my code :
var express = require("express"),
app = express(),
path = require("path");
app.get("/", function( req, res ) {
res.sendfile( path.join(__dirname + '/index.html'));
});
var adminRouter = express.Router();
adminRouter.get('/', function(req, res) {
res.send('I am the dashboard!');
});
app.use("/admin", adminRouter);
app.listen(process.env.PORT, process.env.IP);
console.log("basic app listeners!");
the error I am getting is :
adminRouter.get('/', function(req, res) {
^
TypeError: Cannot read property 'get' of undefined
at Object.<anonymous> (/home/ubuntu/workspace/server.js:16:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:990:3
Can any one help me? I am running my app in cloud9.
thanks in advance!!
Your express version less than +4 , probably version 3. Try
npm uninstall express --save
Then re-install.
adminRouter.get('/', function(req, res) {
res.send('I am the dashboard!');
});
try it like this as well.
adminRouter.route('/').get(function(req,res){
res.json({'hello there from main route!'});
});
Actually this is express version problem.
express.Router(); is supported on version 4.x and cloud 9 support by default 3.x
change your package.json
"express": "^4.15.2",
and delete node_module folder
then run
npm install

Parse server clone install

I clone Repo parse server from parse-server-example and add run mongo db and also install nodejs pacakge via npm install, But when i want to run app with npm start print this error in terminal!!
How i can fix this issue ? it's about nodejs version or what?
Here is my index.js file:
// Example express application adding the parse-server module to expose Parse
// compatible API routes.
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'app',
masterKey: process.env.MASTER_KEY || 'master', //Add your master key here. Keep it secret!
serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse', // Don't forget to change to https if needed
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var app = express();
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
res.status(200).send('Make sure to star the parse-server repo on GitHub!');
});
// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
And by install babel-cli and run show me this:
/Users/sajad/Sites/parse/node_modules/parse-server/node_modules/babel-polyfill/lib/index.js:14
throw new Error("only one instance of babel-polyfill is allowed");
^
Error: only one instance of babel-polyfill is allowed
at Object.<anonymous> (/Users/sajad/Sites/parse/node_modules/parse-server/node_modules/babel-polyfill/lib/index.js:14:9)
at Module._compile (module.js:460:26)
at Module._extensions..js (module.js:478:10)
at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/babel-cli/node_modules/babel-register/lib/node.js:134:7)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/sajad/Sites/parse/node_modules/parse-server/lib/ParseServer.js:9:1)
at Module._compile (module.js:460:26)
This is because this module(or more correctly, a dependency of your module) is using the const keyword which isn't available in your node version (v0.12). Full support for the const keyword came in v6 of node which arrived just this week.
Alternatively you could transpile your project using babel
If you go with the babel route you could do the following in your project root folder
npm install -g babel-cli
babel-node index.js
See babel usage page for more information on how to use babel correctly.
EDIT: In the documentation you provided it explicitly tells you that you must have at least node v4.3 and that you should run the project with the command "npm start". So i'm guessing that this project already has babel, you're just running it incorrectly and with the incorrect node version.

MongoDB - Error: Cannot find module '../build/Release/bson'

I tried to run a typescript example in the following way which caused following error:
$ mongod --dbpath /home/u/databases
$ npm install
$ tsc --sourcemap --module commonjs app.ts
$ node app.js
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
========================================================================================
= Please ensure that you set the default write concern for the database by setting =
= one of the options =
= =
= w: (value of > -1 or the string 'majority'), where < 1 means =
= no write acknowledgement =
= journal: true/false, wait for flush to journal before acknowledgement =
= fsync: true/false, wait for flush to file system before acknowledgement =
= =
= For backward compatibility safe is still supported and =
= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] =
= the default value is false which means the driver receives does not =
= return the information of the success/error of the insert/update/remove =
= =
= ex: new Db(new Server('localhost', 27017), {safe:false}) =
= =
= http://www.mongodb.org/display/DOCS/getLastError+Command =
= =
= The default of no acknowledgement will change in the very near future =
= =
= This message will disappear when the default safe is set on the driver Db =
========================================================================================
/home/u/tmp/TypeScriptSamples/imageboard/app.js:9
app.configure(function () {
^
TypeError: Object function (req, res, next) {
app.handle(req, res, next);
} has no method 'configure'
at Object.<anonymous> (/home/u/tmp/TypeScriptSamples/imageboard/app.js:9:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
Furthermore, looking at db.ts I think http and url are missing in package.json file, am I right?
How is it possible to fix the above error with mongodb?
in Linux operating system first remove bson folder from node_modules and run this command:
sudo apt-get install gcc make build-essential
and then restart nodejs file such as index.js. Hope its helpful
I am using connect-mongo for sessions. I had the same problem and was because the version of connect-mongo generated an error with the version 4.0.x of mongoose. You could check each version of the dependencies you are using.
looking at db.ts I think http and url are missing in package.json file, am I right?
No. These modules are a part of core nodejs.
The source of the error is the package.json specifying minimum numbers without backward in compatible version locks. https://github.com/Microsoft/TypeScriptSamples/blob/master/imageboard/package.json#L6 I would change '>=' to be harder versions e.g. 3.x

Categories

Resources