How to run a custom npm script in an typescript app - node.js

I am using react-typescript in next.js app.
I want to run a npm script that will log out all console.log() present in home page (_app.tsx)
//_app.tsx
...
...
var num = 2
console.log('log this out',num)
I have tried the following commands to check if it works in first place
(found this as a way to run typescript files by node)
1)ts-node _app.tsx
2)tsc helloWorld.ts && node helloWorld.js
3)node _app.tsx
None of them seem to work out

Related

Neutralinojs with vitejs and litElement

I would like to try the NeutralinoJS using viteJS and litElement.
I have followed https://neutralino.js.org/docs/how-to/use-a-frontend-library but i can't get it to work.
What i have tried:
After initializing the neutralinojs app with neu create myapp --template neutralinojs/neutralinojs-zero i can cd into and run npm run. I get an app with the text It works. So i think this step is ok.
Then, like they say in the docs, i cd into the app folder. Here i initialize the vite project with npm create vite#latest
I follow the vite wizard install to create a lit project using typescript
i can then cd into the lit application folder, build it and then run npm run dev, which open the vite example app on the browser. So i think on this step everything is working ok
At this point i can still run the neu run command on the neutralino folder and the app (the neutralino example all with the "It works" text) still runs
Where things go wrong:
On the neutralino-config.json i make the following changes:
"documentRoot": "/my-lit-app/dist/"
"icon": "/my-lit-app/dist/vite.svg"
"resourcesPath": "/my-lit-app/dist/"
"clientLibrary": "/my-lit-app/dist/my-lit-app.js"
run neu update
build the lit app with npm run build inside the my-lit-app folder
run neu run on the neutralino app folder
At this point i get the error: neutralino-mac_x64 quite unexpectedly (an osx alert window) and i get on the console:
neu: INFO Starting process: neutralino-mac_x64 --load-dir-res --path=. --export-auth-info --neu-dev-extension --neu-dev-auto-reload
INFO 2022-10-09 17:06:34,433 Auth info was exported to ./.tmp/auth_info.json api/debug/debug.cpp:14 myname#unknown-host
neu: INFO neutralino-mac_x64 was stopped with success code 0
The my-lit-app entry point is the my-lit-app/index.html.
I think what i want is the neutralino app to open and run this file, but i have no idea why it isn't working

MeteorUp volumes and how Meteor can access to their contents

First, thank you for reading my question. This is my first time on stackoverflow and I made a lot of research for answers that could help me.
CONTEXT
I'm developing a Meteor App that is used as a CMS, I create contents and store datas in mongoDb collections. The goal is to use these datas and a React project to build a static website, which is sent to an AWS S3 bucket for hosting purpose.
I'm using meteorUp to deploy my Meteor App (on an AWS EC2 instance) and according to MeteorUp documentation (http://meteor-up.com/docs.html#volumes), I added a docker volume in my mup.js:
module.exports = {
...
meteor: {
...
volumes: {
'/opt/front': '/front'
},
...
},
...
};
Once deployed, volume is well set in '/opt/myproject/config/start.sh':
sudo docker run \
-d \
--restart=always \
$VOLUME \
\
--expose=3000 \
\
--hostname="$HOSTNAME-$APPNAME" \
--env-file=$ENV_FILE \
\
--log-opt max-size=100m --log-opt max-file=10 \
-v /opt/front:/front \
--memory-reservation 600M \
\
--name=$APPNAME \
$IMAGE
echo "Ran abernix/meteord:node-8.4.0-base"
# When using a private docker registry, the cleanup run in
# Prepare Bundle is only done on one server, so we also
# cleanup here so the other servers don't run out of disk space
if [[ $VOLUME == "" ]]; then
# The app starts much faster when prepare bundle is enabled,
# so we do not need to wait as long
sleep 3s
else
sleep 15s
fi
On my EC2, '/opt/front' contains the React project used to generate a static website.
This folder includes a package.json file, every modules are available in the 'node_modules' directory. 'react-scripts' is one of them, and package.json contains the following script line:
"build": "react-scripts build",
React Project
React App is fed with a JSON file available in 'opt/front/src/assets/datas/publish.json'.
This JSON file can be hand-written (so the project can be developed independently) or generated by my Meteor App.
Meteor App
Client-side, on the User Interface, we have a 'Publish' button that the Administrator can click when she/he wants to generate the static website (using CMS datas) and deploy it to the S3 bucket.
It calls a Meteor method (server-side)
Its action is separated in 3 steps:
1. Collect every useful datas and save them into a Publish collection
2. JSON creation
a. Get Public collection first entry into a javascript object.
b. Write a JSON file using that object in the React Project directory ('opt/front/src/assets/datas/publish.json').
Here's the code:
import fs from 'fs';
let publishDatas = Publish.find({}, {sort : { createdAt : -1}}).fetch();
let jsonDatasString = JSON.stringify(publishDatas[0]);
fs.writeFile('/front/src/assets/datas/publish.json', jsonDatasString, 'utf8', function (err) {
if (err) {
return console.log(err);
}
});
2. Static Website build
a. Run a CD command to reach React Project's directory then run the 'build' script using this code:
process_exec_sync = function (command) {
// Load future from fibers
var Future = Npm.require("fibers/future");
// Load exec
var child = Npm.require("child_process");
// Create new future
var future = new Future();
// Run command synchronous
child.exec(command, {maxBuffer: 1024 * 10000}, function(error, stdout, stderr) {
// return an onbject to identify error and success
var result = {};
// test for error
if (error) {
result.error = error;
}
// return stdout
result.stdout = stdout;
future.return(result);
});
// wait for future
return future.wait();
}
var build = process_exec_sync('(cd front && npm run build)');
b. if 'build' is OK, then I send the 'front/build' content to my S3 bucket.
Behaviors:
On local environment (Meteor running on development mode):
FYI: React Project directory's name and location are slightly different.
Its located in my meteor project directory, so instead of 'front', it's named '.#front' because I don't want Meteor to restart every time a file is modified, added or deleted.
Everything works well, but I'm fully aware that I'm in development mode and I benefit from my local environment.
On production environment (Meteor running on production mode in a docker container):
Step 2.b : It works well, I can see the new generated file in 'opt/front/src/assets/datas/'
Step 3.a : I get the following error:
"Error running ls: Command failed: (cd /front && npm run build)
(node:39) ExperimentalWarning: The WHATWG Encoding Standard
implementation is an experimental API. It should not yet be used in
production applications.
npm ERR! code ELIFECYCLE npm ERR! errno 1 npm
ERR! front#0.1.0 build: react-scripts build npm ERR! Exit status 1
npm ERR! npm ERR! Failed at the front#0.1.0 build script. npm ERR!
This is probably not a problem with npm. There is likely additional
logging output above.
npm ERR! A complete log of this run can be found in: npm ERR!
/root/.npm/_logs/2021-09-16T13_55_24_043Z-debug.log [exec-fail]"
So here's my question:
On production mode, is it possible to use Meteor to reach another directory and run a script from a package.json?
I've been searching for an answer for months, and can't find a similar or nearby case.
Am I doing something wrong?
Am I using a wrong approach?
Am I crazy? :D
Thank you so much to have read until the end.
Thank you for your answers!
!!!!! UPDATE !!!!!
I found the solution!
In fact I had to check few things on my EC2 with ssh:
once connected, I had to go to '/opt/front/' and try to build the React-app with 'npm run build'
I had a first error because of CHMOD not set to 777 on that directory (noob!)
then, I had an error because of node-sass.
The reason is that my docker is using Node v8, and my EC2 is using Node v16.
I had to install NVM and use a Node v8, then delete my React-App node_modules (and package-lock.json) then reinstall it.
Once it was done, everything worked perfectly!
I now have a Meteor App acting as a CMS / Preview website hosted on an EC2 instance that can publish a static website on a S3 bucket.
Thank you for reading me!
!!!!! UPDATE !!!!!
I found the solution!
In fact I had to check few things on my EC2 with ssh:
once connected, I had to go to '/opt/front/' and try to build the React-app with 'npm run build'
I had a first error because of CHMOD not set to 777 on that directory (noob!)
then, I had an error because of node-sass.
The reason is that my docker is using Node v8, and my EC2 is using Node v16.
I had to install NVM and use a Node v8, then delete my React-App node_modules (and package-lock.json) then reinstall it.
Once it was done, everything worked perfectly!
I now have a Meteor App acting as a CMS / Preview website hosted on an EC2 instance that can publish a static website on a S3 bucket.
Thank you for reading me!

Starting Angular application as a default of a NodeJS project

I have a NodeJS application and an Angular 6 as a frontend.
The project looks like:
-> Node Project
---> src
---> Client_App (Anuglar)
To run the application, I need to follow those commands and start the server and angular separately, like:
-> node start
-> cd src/Client_App
-> ng serve
I need to start the two application with one single command or to add my dist file of Angular to be run at the start of my NodeJS, which is using Jade right now.
I am still new to NodeJS and still don't know how to configure it.
Anybody can help? Thanks
Edited:
I have tried now to add the dist folder to my views folder and run it within the app.js
app.get('/', function (req, res, next) {
res.sendFile(path.join(__dirname + '/app_server/views/ngapp/index.html'));
});
But I am receiving the error, that my .js and .css folders are not found:
When you build your application with the CLI ng build --prod, you get a dist folder : this folder contains all of your application, bundled into different files (feel free to look at them).
To be able to create a .ZIP file with that, you will need two things :
this dist folder
an http server
You have the first one, but not the second one.
All you need is a very simple server. For instance, http-server on NPM can do that. By installing it as a dev dependency, you could create a command in your package.json file
"deploy-locally": "http-server ./dist"
And now run it with
npm run deploy-locally
Or even better,
"start": "http-server ./dist"
And run with
npm start
If you don't want to use a NPM package (or forced to use NodeJS), simply create a basic http server in a JS file and run it with your command line (sorry, can't help on that, not into nodeJS right now).
You can create a new route and pass in app.route as express.static as below,
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(path.join(__dirname, 'dist')));
make sure, u have build version of angular application by running this command,
ng build --prod --build-optimizer
You would need express to install in this case. express has amazing ways to handle all this

WebStorm debugging not stopping on breakpoints

My app is a node.js app which I can run through command line using: npm test inside the working directory. In WebStorm, I created a new configuration that looks like this:
Node interpreter: /usr/local/bin/npm
Node parameters: test
Working directory ~/dev/project
When I hit the run button, I get the correct output:
/usr/loca/bin/npm test
> app#1.0.0 test ~/dev/project
something else
Process finished with exit code 0
But since I have breakpoints set, it should have stopped on a breakpoint instead of getting to the Process finished part. I set my code to be pretty simple just so I can test breakpoints, so it looks like this:
"use strict";
let foo = false; (breakpoint)
let bar = true;
if (foo === bar) { (breakpoint)
console.log('something');
} else {
console.log('something else'); (breakpoint)
}
process.exit(1);
I also tried to make this work through command line. In my site settings, I set my Built-in server to port 12345. Can accept external connections, and allow unsigned requests.
when I run it through command line, I use:
npm --debug-brk=12345 test
I get the same result: it runs all the way to the exit point without stopping on the breakpoints.
Any ideas what I need to do to get this to work?
/usr/local/bin/npm is definitely not a Node interpreter, it's NPM package manager that is a Node.js application itself (i.e. it's run with Node.js interpreter). And test is a name of npm script, not a Node.js parameter.
If you like to debug your .js file that is run via npm test, you need to modify your npm script to include the debug options and then use NPM run configuration for debugging. Or, just create a Node.js configuration, set a valid path to Node.js execuitable there (/usr/bin/node or whatever it looks like on your system), then specify your .js file as JavaScript file:. See https://blog.jetbrains.com/webstorm/2017/09/debugging-node-js-apps-in-webstorm for more info

How to install node.js and create project in Eclipse

The steps I've tried:
1.(OK) install node from official website: https://nodejs.org/en/download/
Result: I'm able to open cmd(in any location, type node then use commands like "console.log" and it prints my messages)
2.(Failure) install express using npm install -g express from cmd gives me an error(picture attached
3.(OK) I've succeed installing express using the following command npm install express (without -g)
4.(OK) Writing a simple Hello World program works. Javascript file:
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
5.(Failure) However, I wanna run a bigger project, where besides one js file, I also have an index.html file. If I move both files to node installation directory, everything works. But I wanna be able to keep my projects somewhere else. If I try to run with node C:\Users\marius\Downloads\chat-example-master\indes.js I get the error: Cannot find module express. Thus it seems that when I installed express without "-g" I got it working only in node directory.(let me know if you have any doubt).
6.(Failure) When creating a Node.js project from Eclipse, I choose empty project, no template, then add a single and simple js file(the one with Hello World), right click on project name -> run as -> run Configuration -> Node Application -> New -> add my .js file -> Run. I get the following error:
Exception occurred executing command line.(steps from http://techprd.com/how-to-setup-node-js-project-in-eclipse/)
Cannot run program "node" (in directory "C:\Users\marius\workspace\FirstNodeProject"): CreateProcess error=2, The system cannot find the file specified
To recap: What I want is to be able to run node projects located anywhere with "node" in cmd and to create node.js and express project and run them from Eclipse.
Please let me know if you need more information.
Just to let others know if they come across this issue. I can run express apps from anywhere but in the root folder of every app I have to npm install express.
In Eclipse all you need to do is: Window->Preferences->Nodeclipse->uncheck "find .Node on PATH" and insert into Node.js path input your node.exe location (in my case: C:\Program Files\nodejs\node.exe)

Resources