Node - how to run app.js? - node.js

I am very new to Node.js and I tried to run a project (made by other developer) by having a command in terminal node app.js. But I encountered below error, do you have any idea how to run this project?
I followed few instructions here to run a project.
Error logs below:
Junryls-Mac-mini:app junrylmaraviles$ node app.js
/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1
(function (exports, require, module, __filename, __dirname) { define('src/app'
^
ReferenceError: define is not defined
at Object.<anonymous> (/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1:63)
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:902:3

Assuming I have node and npm properly installed on the machine, I would
Download the code
Navigate to inside the project folder on terminal, where I would hopefully see a package.json file
Do an npm install for installing all the project dependencies
Do an npm install -g nodemon for installing all the project dependencies
Then npm start OR node app.js OR nodemon app.js to get the app running on local host
use nodemon app.js ( nodemon is a utility that will monitor for any changes in your source and automatically restart your server)

The code downloaded may require you to install dependencies first. Try commands(in app.js directory): npm install then node app.js. This should install dependencies and then start the app.

Just adding this.
In your package.json, if your "main": "index.js" is correctly set. Just use node .
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
...
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
...
},
"devDependencies": {
...
}
}

To run app.js file check "main": "app.js" in your package.json file.
Then run command $ node app.js That should run your app.

Node is complaining because there is no function called define, which your code tries to call on its very first line.
define comes from AMD, which is not used in standard node development.
It is possible that the developer you got your project from used some kind of trickery to use AMD in node. You should ask this person what special steps are necessary to run the code.

To run a node js project you can run the project by below commands
node app.js
But if you want to run your project with npm start then you need to pass "start": "Node app.js" in the scripts of the package.json file
So, your package.json file will look like below
"scripts": { "start": "node app.js", "test": "test" }
Once you are done with the changes then you just need to save the file and then go to the terminal hit the npm start command you will see that the project started as its working on the node app.js command
Refer to below image for clarification
You can also see in the below image that your project runs on both command node app.js as well as npm start

If the Node Js Project :
Normally we can run,
>node app
(or)
Install nodemon dependency (npm i -g nodemon)
>nodemon app.js
(or)
In Package.json, inside the scripts has "start":"nodemon app.js"
>npm start

you have a package.json file that shows the main configuration of your project,
and a lockfile that contains the full details of your project configuration such as the urls that holds each of the package or libraries used in your project at the root folder of the project......
npm is the default package manager for Node.js....
All you need to do is call $ npm install from the terminal in the root directory where you have the package.json and lock file ...since you are not adding any particular package to be install ..... it will go through the lock file and download one after the other, the required packages from their urls written in the lock file if it isnt present in the project enviroment .....
you make sure you edit your package.json file .... to give an entry point to your app..... "name":"app.js" where app.js is the main script .. or index.js depending on the project naming convention...
then you can run..$ Node app.js or $ npm start if your package.json scripts has a start field config as such "scripts": { "start": "Node index.js", "test": "test" }..... which is indirectly still calling your $ Node app.js

in package.json file add the script
"start":"node filename.js"
and run in terminal - > npm start

Node manages dependencies ie; third party code using package.json so that 3rd party modules names and versions can be kept stable for all installs of the project. This also helps keep the file be light-weight as only actual program code is present in the code repository. Whenever repository is cloned, for it to work(as 3rd party modules may be used in the code), you would need to install all dependencies.
Use npm install on CMD within root of the project structure to complete installing all dependencies. This should resolve all dependencies issues if dependencies get properly installed.

const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Related

webpack script in package.json

I have a question regarding the script property in package.json of my app. If I type npm start, the app gets compiled successfully. And it seems that by typing the above command, www file starts running.
However, if I type npm webpack, nothing happens. I have a react/express app. And the server runs on localhost:3000 on npm start. I want to know, is webpack serving both react and express? I am able to send requests from the client to the server and show the result on the client-side. I just wanted to know how things are working.
"scripts": {
"start": "NODE_ENV=development nodemon ./bin/www",
"webpack": "webpack-dev-server --config ./webpack.config.js --mode development"
}
for other scripts than "start", you have to type npm run [scriptname].
in your case: npm run webpack

How to run a node app in another machine without nodemon installed as global

I am building an app using nodejs and express framework and have installed nodemon globally to restart the server automatically.
Now if I take this app and run in another machine/host/environment (without nodemon installed globally) then it would produce an error because package.json doesn't contain nodemon as a dependency.
What would be the best way to fix this?
Include nodemon in your package.json as a dev dependency. So it will be available in the context of the script.
{
"scripts": {
"start": "nodemon my_file.js"
},
"devDependencies": {
"nodemon": "<version>",
}
}
Then from the terminal you can use npm start
Nodemon has been the goto for a long time, but now with Node.js 19, we have --watch flag, which restarts server when files changes. Keep in mind this is experimental
Docs
:)

can i install a package locally and globally at same time in node.js?

I am working on a project. I have worked with nodemon that is installed globally for development.
I edited my package.json file to add a script to automatically run a nodemon script - as shown below:
"scripts": {
"start": "node ./bin/www",
"dev": "nodemon -e js,pug"
}
Now when another developer runs:
npm start dev
they will surely get a error if they have not installed the nodemon module.
I know that the solution is to install nodemon locally as a development dependency.
Is it possible to work around this problem without installing it locally?
Can I install nodemon both locally and globally at the same time?
simply install it globally and you can use it in any of your project
command :
npm i -g nodemon
now you don't need to install it locally at all to make it work on your project.

How do I deploy my Typescript Node.js app to Heroku?

When testing locally I was previously running:
"build-live": "nodemon --exec ./node_modules/.bin/ts-node -r dotenv/config -- ./index.ts"
I then figured my Procfile should be something like:
web: ./node_modules/.bin/ts-node -- ./index.ts
But it says module 'typescript' not found, even when it is in package.json. I read in a few places that ts-node is not the way to go to deploy to Heroku, so I am not sure what to do.
UPDATE: I think I am supposed to compile it, so I tried:
web: ./node_modules/.bin/tsc --module commonjs --allowJs --outDir build/ --sourceMap --target es6 index.ts && node build/index.js
This succeeds, however when actually running it, a bunch of the libs I'm using get "Cannot find module '...'".
Alternatively you can have the TypeScript compile as a postinstall hook and run node build/index.js as the only Procfile command:
Your package.json should contain a postinstall hint that gets executed after npm install and before the node process launches:
"scripts": {
"start": "node build/index.js",
"build": "tsc",
"postinstall": "npm run build"
}
You can then leave your Procfile as is:
web: npm start
This 'build on deploy' approach is documented by Heroku here.
The command you've given Heroku is to launch the web "process" by compiling index.ts and dependencies and starting node at index.js. Depending on how things are timed, index.js might or might not exist at the time node starts.
You need to already have your sources compiled by the time you want to start your app. For example, web should just be web: node index.js or similar.
Each build process is different, so you need to figure that out for your own setup. But, suppose you have a classical setup where you push to git and then Heroku picks up that change and updates the app with the new slug. You could just compile things locally and include index.js and any other build output in the repository, for it to be available in the slug for Heroku to use.
A better approach is to use a build server which has an integration with Heroku. After you do the build there, configure it to send the build results to Heroku. Travis has a straighforward setup like this. This way you don't need to include build outputs in your repository, which is considered an anti-pattern.
On a sidenode, try using a tsconfig.json to keep the tsc configuration. It will save you from having to write such long command lines all over the place.
Fabian said that we could do something like:
"scripts": {
"start": "node build/index.js",
"build": "tsc",
"postinstall": "npm run build"
}
As of me writing this, I tested this and can state: postinstall is not required since build script is ran by Heroku. If you want to do it without build script, then you can use heroku-postbuild which will run after dependencies are installed there you run tsc to compile.
My problem was about missing Typescript npm modules. The Typescript compiler tsc was not found when deployed the app to Heroku.
The Heroku deploy process (rightly) does not install development dependencies, in my case the Typescript module was part of devDependencies and thus the tsc command was not running on the Heroku platform.
Solution 1
Add typescript to dependencies: npm i typescript -s
Solution 2
Open Heroku console:
Select console type:
Run the command npm i typescript && npm run tsc
Install typescript as a dev dependency (cf. https://www.typescriptlang.org/download). Once built, your app does not need typescript anymore!
npm install -D typescript
Then in your package.json:
{
"main": "index.js", // <- file will be generated at build time with `tsc`
"scripts": {
"build": "tsc",
"start": "node ."
"start:dev": "ts-node index.ts" // idem, install ts-node as a dev dependency
}
}
The key point here is "build": "tsc".
Why?
Heroku does install all dependencies during build and remove the dev dependencies before the app is deployed (source here).
Node.js deployments will automatically execute an app’s build script during build (since March 11. 2019 source here)
In package.json
"scripts": {
"tsc": "./node_modules/typescript/bin/tsc",
"postinstall": "npm run tsc"
},
Works for me for Heroku deployment.
Installing typescript npm install -D typescript and writing tsc in the build script "build": "tsc", does not work for me. Also, try to run npm i typescript && npm run tsc in the Heroku console which also does not work.
In my case, I remove some dependencies from "devDependencies" to "dependencies", so it goes like this:
"dependencies": {
// The other dependencies goes here, I don't touch them.
// But all TS dependencies I remove to here.
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.2.3",
"ts-loader": "^8.0.18"
},

Node error: SyntaxError: Unexpected token import

I don't understand what is wrong. I checked other forum talking about transpilation and babel. What do I have to do?
node -v
v5.5.0
my code:
import recast from 'recastai'
and the error
(function (exports, require, module, __filename, __dirname) { import recast from 'module1'
^^^^^^
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:139:18)
at node.js:999:3
ES6 imports are a recently introduced feature and the current stable version of Node does not support them yet. Node.js issue tracker has an open issue for this - but until V8 and Node add support for this feature, you will need to use a transpiler (most popular one being babel) to be able to use imports.
For quickly trying out transpilation, babel provides a web based REPL. This one demonstrates your code being transpiled.
The babel project homepage points to the relevant resources for getting started with Babel and integrating it with your development workflow.
For the simplest setup, visit this setup page and select CLI in the Babel built-ins section.
This basically involves three simple steps:
Install babel-cli : npm install --save-dev babel-cli babel-preset-es2015
Create .babelrc configuration file: echo '{ "presets": ["es2015"] }' > .babelrc
Use the installed module to transpile your source code: ./node_modules/.bin/babel src -d lib
The aforementioned setup page also illustrates how to add an npm script to simplify the last step. Alternatively you can integrate babel with your editor or build chain so that your files are automatically compiled on change.
In case you don't want to deal with babel. This one worked for me.
const calc = require('./my_calc');
let {add, multiply} = calc;
1) Install the latest presets
yarn add --dev babel-preset-latest
2) Create .babelrc and add the following
{
"presets": ["latest"]
}
3) Run your script
npx babel-node yourscript.js
Or in your package.json file add
"scripts": {
"start": "babel-node index.js"
}
Getting Started
First we'll install babel-cli.
$ npm install --save-dev babel-cli
Along with some presets.
$ npm install --save-dev babel-preset-es2015 babel-preset-stage-2
package.json:
"scripts": {
"start": "babel-node index.js --presets es2015,stage-2"
}
run:
$ npm start
Watching file changes with nodemon:
We can improve our npm start script with nodemon.
$ npm install --save-dev nodemon
Then we can update our npm start script.
package.json:
"scripts": {
"start": "nodemon index.js --exec babel-node --presets es2015,stage-2"
}
run:
$ npm start
If you are using pm2, then follow these steps:
$ pm2 start app.js --interpreter babel-node
Its very simple to resolve this issue, import is ES6 syntax and Node has difficulty in supporting it, you need to add Babel as a transpiler, go to package.json and add the following
First add a script tag to use babel while running the JS code for transpiling.
"scripts": {
"start": "nodemon ./app.js --exec babel-node -e js"
}
And then add the following as the Babel devDependencies
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1"
}
after this you also need to configure the babel presets file, therefore create .babelrc file at the root directory and define the presets as follows
{
"presets": [
"es2015",
"stage-0"
]
}
Don't forget to do an npm install in the end
Thanks to a NodeJS enhancement proposal we have a path forward. You can use #standard-things/esm
Find the announcement here Simply run
npm i --save #std/esm
In your packaged today.

Resources