Docker :: Node Hello World Example :: SyntaxError: Invalid or unexpected token? - node.js

I am trying to run this hello world example on node within a docker container
https://medium.com/#adnanrahic/hello-world-app-with-node-js-and-express-c1eb7cfa8a30
Here is my dockerfile:
#escape=`
FROM microsoft/nanoserver
ADD https://nodejs.org/dist/v8.11.1/node-v8.11.1-win-x64.zip C:\node-v8.11.1-win-x64.zip
RUN powershell -Command Expand-Archive C:\node-v8.11.1-win-x64.zip C:\; Rename-Item C:\node-v8.11.1-win-x64 node; `
SETX PATH C:\node;
SHELL ["powershell", "-Command"]
RUN mkdir hello-world; `
cd c:\hello-world; `
npm init -f; `
(Get-Content C:\hello-world\package.json) | `
ForEach-Object { $_ -replace 'index.js', 'app.js' } | `
Set-Content C:\hello-world\package.json; `
npm install express --save; `
echo \""var express = require('express');\"" > app.js; `
echo \""var app = express();\"" >> app.js; `
echo \""app.get('/', function (req, res) {\"" >> app.js; `
echo \"" res.send('Hello World!');\"" >> app.js; `
echo \""});\"" >> app.js; `
echo \""app.listen(3000, function () {\"" >> app.js; `
echo \"" console.log('Example app listening on port 3000!');\"" >> app.js; `
echo \""});\"" >> app.js; `
del c:\node-v8.11.1-win-x64.zip
EXPOSE 3000
ENTRYPOINT node c:\hello-world\app.js
after building the container successsfully:
docker build . -t nano-node-hw
and run it, I get the following error:
PS C:\Users\user\Docker\Node> docker run -it -p 3000:3000 --name node-hello nano-node-hw
c:\hello-world\app.js:1
(function (exports, require, module, __filename, __dirname) { ??v
^
SyntaxError: Invalid or unexpected token
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
I did these same steps on my laptop (Windows 10) running node locally and had no issues.. what gives??

Related

Launchd Bash and Node

I have a script as a .plist registered in /Library/LaunchDaemons - on a particular IO event, this script triggers a bash script that lives in /usr/local/bin (root:admin 0755).
Bash script runs a nodejs script
This is the bash script:
if [[ $(ioreg -p IOUSB | grep Realforce -c) > 0 ]]; then
echo "Realforce is present"
echo 1
echo $(node ./lgtvcontrol/TVinputChange.js mac)
echo 2
else
echo "Realforce not detected"
fi
When I run the bash script as root I get this output:
Realforce is present
1
mac 3166798437680e8a22c7093bf294fbaf connecting connected app com.webos.app.hdmi3
2
When the bash script runs through the LaunchDaemon with UserName root, it gets this output:
Realforce is present
1
2
I don't get why LaunchDaemon fails to run the node script. Any idea or experience with this?
Thank you!!!
Edit 1:
By adding the following key to the plist, I'm able to get an error in node now.
<dict>
<key>PATH</key>
<string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin/lgtvcontrol</string>
</dict>
When outputting the node error log to a file, I get this on execution:
internal/validators.js:113
throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
at validateString (internal/validators.js:113:11)
at Object.join (path.js:1039:7)
at module.exports (/usr/local/bin/lgtvcontrol/node_modules/persist-path/index.js:9:27)
at new LGTV (/usr/local/bin/lgtvcontrol/index.js:48:16)
at LGTV (/usr/local/bin/lgtvcontrol/index.js:38:16)
at Object.<anonymous> (/usr/local/bin/lgtvcontrol/TVinputChange.js:7:33)
at Module._compile (internal/modules/cjs/loader.js:1121:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1160:10)
at Module.load (internal/modules/cjs/loader.js:976:32)
at Function.Module._load (internal/modules/cjs/loader.js:884:14) {
code: 'ERR_INVALID_ARG_TYPE'
}

How do i specify the path in node/express correctly to read my certificate files?

This is my file structure simplified
app-folder
-> dist
-> server.js
-> src
-> server.ts
-> key.pem
-> cert.pem
This is the simplified content of the server.ts file to read the certificate files
import fs from 'fs';
const options = {
key: fs.readFileSync('../key.pem'),
cert: fs.readFileSync('../cert.pem')
};
This is the error i am getting
server | internal/fs/utils.js:307
server | throw err;
server | ^
server |
server | Error: ENOENT: no such file or directory, open '../key.pem'
server | at Object.openSync (fs.js:476:3)
server | at Object.readFileSync (fs.js:377:35)
server | at Object.<anonymous> (/usr/src/app/dist/server.js:18:23)
server | at Module._compile (internal/modules/cjs/loader.js:1063:30)
server | at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
server | at Module.load (internal/modules/cjs/loader.js:928:32)
server | at Function.Module._load (internal/modules/cjs/loader.js:769:14)
server | at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
server | at internal/main/run_main_module.js:17:47 {
server | errno: -2,
server | syscall: 'open',
server | code: 'ENOENT',
server | path: '../key.pem'
server | }
server exited with code 1
I created the key and certificate following this
tutorial
Hoangdv pointed out that i use docker which is correct this is my Dockerfile:
FROM node:14
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
RUN npm install -g nodemon
# Install dependencies
COPY package.json .
RUN npm install
# Bundle app source
COPY . .
RUN npx tsc
EXPOSE 8080
Does COPY . . not copy the certificates already?
Relative paths will be resolved relative to the current working directory as determined by calling process.cwd().
--- node.js docs
import fs from 'fs';
import path from 'path';
const options = {
key: fs.readFileSync(path.resolve(__dirname, '../key.pem')),
cert: fs.readFileSync(path.resolve(__dirname, '../cert.pem'))
};
Try,
var resolve = require('path').resolve
key : resolve('../key.pem')
cert : resolve('../cert.pem')

SyntaxError when declaring a class in TypeScript

I'm getting an error when declaring a class:
// This is all on my test1.ts file content
class WDesign {
wModel: string;
wQuer: string;
}
let logWDesign = (wd : WDesign) => {
console.log(wd.wModel + " " + wd.wQuer);
}
let wd1 : WDesign;
wd1.wModel = "SDS-9985";
wd1.wQuer = "escarni";
logWDesign(wd1);
Then, to show on Node command prompt:
>node test1.ts
I get the following:
[filePath].test1.ts:3
wModel: string;
^
SyntaxError: Unexpected token :
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3
Typescript ver 3.1.3
Node ver. 8.12.0
Visual Studio Code 1.28.2
You firstly have to transpile the .ts file .js by simply running the command
tsc
node test1.js
This will generate javascript corresponding to your typescript files. Node cannot directly understand typescript. You have to give it javascript code.
You can use typescript-node-starter code provided by Typescript here to save configuration hustle.
Post comments if further help is required.

installing and running browsershots

I tried to install Brwoswershots (https://github.com/spatie/browsershot) and I did this exactly by following the instructions on github.
Installing NodeJS and npm via yum
Installing browswershoots via composer: composer require
satie/browsershot
crated a file with
use Spatie\Browsershot\Browsershot;
$pathToImage="img/testasdf.png";
// an image will be saved
Browsershot::url('https://example.com')
->setScreenshotType('jpeg', 100)
->save($pathToImage);
It is on http://textblob.com/browsershots.php and brings the error.
Fatal error: Uncaught
Symfony\Component\Process\Exception\ProcessFailedException:
The command "PATH=$PATH:/usr/local/bin NODE_PATH=`npm root -g` node
'/home/textblob/public_html/vendor/spatie/browsershot/src/../bin/browser.js'
'{"url":"https:\/\/example.com",
"action":"screenshot",
"options": {
"type":"jpeg",
"path":"img\/testasdf.png",
"quality":100,
"args":[],
"viewport":{"width":800,"height":600}
}
}'"
failed. Exit Code: 1(General error) Working directory:
/home/textblob/public_html
Output: ================ Error Output: ================
/home/textblob/public_html/vendor/spatie/browsershot/bin/browser.js:5
const getOutput = async (page, request) =>
{ ^ SyntaxError: Unexpected token ( at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.runMa in /home/textblob/public_html/vendor/spatie/browsershot/src/Browsershot.php
on line 565
I could solve this by downgrading to boxshot v2, witch works without puppeteer and so its not a fix, but working for me.

How to deploy a phantomjs node app on AWS Lambda?

I threw together a small Lambda function together to crawl a website using the SpookyJS, CasperJS, and PhantomJS toolchain for headless browsing. The task is quite simple, and at some point a few months ago it was working in Lambda. I recently had to change a few things around and wanted to work on the project again, but started fresh and had trouble getting Lambda to run without erroring in any capacity. My question is how can I run phantomjs in Lambda?
The example code I am running is:
spooky.start('http://en.wikipedia.org/wiki/Spooky_the_Tuff_Little_Ghost');
spooky.then(function () {
this.emit('hello', 'Hello, from ' + this.evaluate(function () {
return document.title;
}));
});
spooky.run();
The error I am getting in Lambda is:
{ [Error: Child terminated with non-zero exit code 1] details: { code: 1, signal: null } }
I have followed a variety of procedures to ensure everything is able to run on Lambda. Below is a long list of things I've attempted to diagnose:
Run locally using node index.js and confirm it is working
Upload package.json and the js file to an Amazon Linux EC2 instance for compilation as recommended for npm installation calls and described here
Run npm install on the ec2 instance, and again run node index.js to ensure the correct output
zip everything up, and deploy to AWS using the cli
My package.json is:
{
"name": "lambda-spooky-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"casperjs": "^1.1.3",
"phantomjs-prebuilt": "^2.1.10",
"spooky": "^0.2.5"
}
}
I have also attempted the following (most also working locally, and on the AWS EC2 instance, but with the same error on Lambda:
Trying the non -prebuilt version of phantom
Ensuring casperjs and phantomjs are accessible from the path with process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'] + ':' + process.env['LAMBDA_TASK_ROOT'] + '/node_modules/.bin';
console.log( 'PATH: ' + process.env.PATH );
Inspecting spawn calls by wrapping child_process's .spawn() call, and got the following:
{ '0': 'casperjs',
'1':
[ '/var/task/node_modules/spooky/lib/bootstrap.js',
'--transport=http',
'--command=casperjs',
'--port=8081',
'--spooky_lib=/var/task/node_modules/spooky/lib/../',
'--spawnOptions=[object Object]' ],
'2': {} }
Calling .exec('casperjs') and .exec('phantomjs --version') directly, confirming it works locally and on EC2, but gets the following error in Lambda. The command:
`require('child_process').exec('casperjs', (error, stdout, stderr) => {
if (error) { console.error('error: ' + error); }
console.log('out: ' + stdout);
console.log('err: ' + stderr);
});
both with the following result:
err: Error: Command failed: /bin/sh -c casperjs
module.js:327
throw err;
^
Error: Cannot find module '/var/task/node_modules/lib/phantomjs'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/task/node_modules/.bin/phantomjs:16:15)
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)
2016-08-07T15:36:37.349Z b9a1b509-5cb4-11e6-ae82-256a0a2817b9 sout:
2016-08-07T15:36:37.349Z b9a1b509-5cb4-11e6-ae82-256a0a2817b9 serr: module.js:327
throw err;
^
Error: Cannot find module '/var/task/node_modules/lib/phantomjs'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/task/node_modules/.bin/phantomjs:16:15)
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)
I found the issue to be that including the node_modules/.bin in the path works on both local and ec2 machines because those files simply point to the action /bin folders in each respective library. This breaks if calls within those files use relative paths. The issue:
[ec2-user#ip-172-31-32-87 .bin]$ ls -lrt
total 0
lrwxrwxrwx 1 ec2-user ec2-user 35 Aug 7 00:52 phantomjs -> ../phantomjs-prebuilt/bin/phantomjs
lrwxrwxrwx 1 ec2-user ec2-user 24 Aug 7 00:52 casperjs -> ../casperjs/bin/casperjs
I worked around this by adding each library's respective bin to the lambda path in the Lambda handler function:
process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT']
+ ':' + process.env['LAMBDA_TASK_ROOT'] + '/node_modules/phantomjs-prebuilt/bin'
+ ':' + process.env['LAMBDA_TASK_ROOT'] + '/node_modules/casperjs/bin';
And this will now run phantom, casper, and spooky correctly in Lambda.

Resources