How to solve BuildJobExitNonZero on Digital Ocean - javascript

Hi guys its my first time trying digital ocean,
I am deploying my app via Launch App and my code are hosted on github however when i try importing the code and building i am getting the below error and i have no idea what that is
Please help
2021-08-03T21:47:06.796342084Z => Initializing build
2021-08-03T21:47:06.832099453Z => Retrieving source code to /workspace
2021-08-03T21:47:06.860459803Z => Selecting branch "main"
2021-08-03T21:47:09.561399472Z => Checking out commit "9be192339cd0a8c93919eaf5959bd43c5ff06927"
2021-08-03T21:47:12.318858786Z => Got source_dir: /
2021-08-03T21:47:12.344366201Z => Using workspace root /workspace
2021-08-03T21:47:12.414846752Z
2021-08-03T21:47:12.414907116Z => Building app using buildpacks
2021-08-03T21:47:12.704652275Z => Injecting app environment variables:
2021-08-03T21:47:12.704707986Z QUEUE_CONNECTION DB_HOST SESSION_LIFETIME TWILIO_ACCOUNT_SID SENTRY_TRACES_SAMPLE_RATE APP_URL SENTRY_LARAVEL_DSN TWILIO_AUTH_TOKEN MAIL_MAILER TEXTTAWK_ENVIRONMENT DB_PASSWORD API_SECRET TWILIO_PHONE_NUMBER PERSONAL_CLIENT_ID MAIL_USERNAME MAIL_FROM_ADDRESS PERSONAl_CLIENT_SECRET MULTI_DB_ENABLED BROADCAST_DRIVER APP_ENV GOOGLE_CLIENT_ID EXPANDED_LOGGING ERROR_EMAIL MAIL_PASSWORD GOOGLE_CLIENT_SECRET APP_NAME TRUSTED_PROXIES MAIL_HOST DB_CONNECTION APP_DEBUG DB_USERNAME GOOGLE_REDIRECT_URI APP_KEY CACHE_DRIVER MAIL_ENCRYPTION SESSION_DRIVER INTERNAL_QUEUE_ENABLED MAIL_FROM_NAME DB_PORT DB_DATABASE MAIL_PORT TEXTTAWK_ORGANIZATION_ID
2021-08-03T21:47:12.736297358Z => Configuring custom build command to be run at the end of the build:
2021-08-03T21:47:12.761828497Z composer install
2021-08-03T21:47:13.365839056Z => Running buildpack detection
2021-08-03T21:47:13.365923629Z
2021-08-03T21:47:14.074627212Z heroku/nodejs-engine 0.5.0
2021-08-03T21:47:14.074682595Z digitalocean/node 0.3.4
2021-08-03T21:47:14.074757668Z digitalocean/php-appdetect 0.0.3
2021-08-03T21:47:14.074803894Z heroku/php 0.188.4
2021-08-03T21:47:14.075038595Z digitalocean/procfile 0.0.3
2021-08-03T21:47:14.075058351Z digitalocean/custom 0.1.0
2021-08-03T21:47:14.202672749Z
2021-08-03T21:47:14.202717224Z For documentation on the buildpacks used to build your app, please see:
2021-08-03T21:47:14.202743590Z Node.js: https://do.co/apps-buildpack-node
2021-08-03T21:47:14.202798824Z PHP: https://do.co/apps-buildpack-php
2021-08-03T21:47:14.818696983Z
2021-08-03T21:47:14.818882813Z => Building app
2021-08-03T21:47:14.818924263Z
2021-08-03T21:47:15.093655477Z ---> Node.js Buildpack
2021-08-03T21:47:15.108387965Z ---> Installing toolbox
2021-08-03T21:47:15.129668030Z ---> - jq
2021-08-03T21:47:15.847171368Z ---> - yj
2021-08-03T21:47:16.137897473Z ---> Getting Node version
2021-08-03T21:47:16.185826122Z ---> Resolving Node version
2021-08-03T21:47:18.820896954Z ---> Downloading and extracting Node v12.22.4
2021-08-03T21:47:33.310168979Z ---> Parsing package.json
2021-08-03T21:47:34.458500684Z ---> No file to start server
2021-08-03T21:47:34.458547440Z ---> either use 'docker run' to start container or add index.js or server.js
2021-08-03T21:47:34.543028305Z Error: package-lock.json does not exist. Please commit either a package-lock.json or yarn.lock file to your repository and try again.
2021-08-03T21:47:34.543513537Z project does not contain a package manager lockfile
2021-08-03T21:47:34.546474624Z [31;1mERROR: [0mfailed to build: exit status 1
2021-08-03T21:47:37.973947707Z
2021-08-03T21:47:37.974088341Z For documentation on the buildpacks used to build your app, please see:
2021-08-03T21:47:37.974111872Z Node.js: https://do.co/apps-buildpack-node
2021-08-03T21:47:37.974199168Z PHP: https://do.co/apps-buildpack-php
2021-08-03T21:47:37.977558349Z
2021-08-03T21:47:37.977966439Z [31m ! Build failed (145)[0m

For anyone who might face this same challenge in the future,
for me the problem was "package.json"
if you deploying a Laravel API you need to delete the package.json file from your project. For me that was the issue that was preventing my project from building
Happy coding

I had a similar error and fixed it a different way. Since the error said "package-lock.json does not exist.", I added a package-lock.json file by running the npm install command in the root directory of the app, the one with the package.json file. After that the app deployed successfully.

Related

Adding opentelemetry tracing to Node.js app breaks `require("fs").realpathSync.native`

Using the following tracing enabling script from OpenTelemetry docs:
const opentelemetry = require("#opentelemetry/sdk-node");
const { getNodeAutoInstrumentations } = require("#opentelemetry/auto-instrumentations-node");
const { diag, DiagConsoleLogger, DiagLogLevel } = require('#opentelemetry/api');
// For troubleshooting, set the log level to DiagLogLevel.DEBUG
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO);
const sdk = new opentelemetry.NodeSDK({
traceExporter: new opentelemetry.tracing.ConsoleSpanExporter(),
instrumentations: [getNodeAutoInstrumentations()]
});
sdk.start()
running my Next.js server as I thought is required, I get an error:
$ node --require './tracing/opentelemetry.js' ./node_modules/next/dist/bin/next start -p 3000
No modules instrumentation has been defined, nothing will be patched
#opentelemetry/instrumentation-grpc Module #grpc/grpc-js has been loaded before #opentelemetry/instrumentation-grpc so it might not work, please initialize it before requiring #grpc/grpc-js
Exporter "otlp" requested through environment variable is unavailable.
/mnt/vol/.local/share/pnpm/global/5/.pnpm/next#12.1.5_zpnidt7m3osuk7shl3s4oenomq/node_modules/next/dist/lib/get-project-dir.js:40
const realDir = _fs.default.realpathSync.native(resolvedDir);
^
TypeError: _fs.default.realpathSync.native is not a function
at Object.getProjectDir (/mnt/vol/.local/share/pnpm/global/5/.pnpm/next#12.1.5_zpnidt7m3osuk7shl3s4oenomq/node_modules/next/dist/lib/get-project-dir.js:40:50)
at nextStart (/mnt/vol/.local/share/pnpm/global/5/.pnpm/next#12.1.5_zpnidt7m3osuk7shl3s4oenomq/node_modules/next/dist/cli/next-start.js:80:37)
at /mnt/vol/.local/share/pnpm/global/5/.pnpm/next#12.1.5_zpnidt7m3osuk7shl3s4oenomq/node_modules/next/dist/bin/next:141:34
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Node.js v17.8.0
Now this can be simplified to a minimal reproduction as follows. This has the fs.realpathSync.native function:
$ node -e 'console.log(require("fs").realpathSync)'
[Function: realpathSync] { native: [Function (anonymous)] }
This doesn't have fs.realpathSync.native:
$ node --require ./tracing/opentelemetry.js -e 'console.log(require("fs").realpathSync)'
No modules instrumentation has been defined, nothing will be patched
#opentelemetry/instrumentation-grpc Module #grpc/grpc-js has been loaded before #opentelemetry/instrumentation-grpc so it might not work, please initialize it before requiring #grpc/grpc-js
[Function (anonymous)]
Exporter "otlp" requested through environment variable is unavailable.
My Node's --require is working correctly (noop.js is an empty file):
$ node --require ./tracing/noop.js -e 'console.log(require("fs").realpathSync)'
[Function: realpathSync] { native: [Function (anonymous)] }
Why would the OpenTelemetry setup script break the fs module?
$ node --version
v17.8.0
//package.json dependencies
"#opentelemetry/api": "^1.3.0",
"#opentelemetry/auto-instrumentations-node": "^0.35.0",
"#opentelemetry/sdk-node": "^0.34.0",
$ uname -a
Linux code-server 5.15.0-1025-oracle #31~20.04.2-Ubuntu SMP Tue Nov 29 13:01:56 UTC 2022 aarch64 aarch64 aarch64 GNU/Linux
Does my ARM machine have something to do with it?
I can reproduce the same on x86_64 on https://replit.com/#JakubKoralewski/opentelemetry-repro with the same behavior.
The reason this error occurs is due to a bug in #opentelemetry/instrumentation-fs introduced as a new dependency to #opentelemetry/auto-instrumentations-node in PR #981 which got released with version 0.34.0. The issue was reported but at the time of writing is still open. However, as also already linked above a PR to address the issue is being reviewed.
Fow now, I see three ways to address the problem:
As suggested in a comment above downgrade #opentelemetry/auto-instrumentations-node to next lower version 0.33.1.
Disable the file system instrumentation when configuring the node instrumentation. For that simply replace getNodeAutoInstrumentations() with getNodeAutoInstrumentations({ '#opentelemetry/instrumentation-fs': { enabled: false } }) in your code. Given that your project is in Next.js and you likely have little file system activity aside from maybe public files this is likely the best option for now.
Remove #opentelemetry/auto-instrumentations-node altogether and simply instrument the libraries you actually use. Using the auto instrumentation for Node.js pulls in a lot of transitive dependencies. Say you have a Next.js app, connect to a Postgres database and use winston for logging your instrumentation setup could look something like this:
const sdk = new opentelemetry.NodeSDK({
traceExporter: new opentelemetry.tracing.ConsoleSpanExporter(),
instrumentations: [
// new FsInstrumentation(), TODO: re-enable once bug is fixed
new HttpInstrumentation(),
new PgInstrumentation(),
new WinstonInstrumentation(),
]
});

React native 0.62.0 Build is failing on Xcode 13.1

I am trying to run my project to Xcode 13.1 but the problem is that build is failing with message:
error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by opening Ajman.xcworkspace. Run CLI with --verbose flag for more details.
Command line invocation:
/Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -workspace Ajman.xcworkspace -configuration Debug -scheme Ajman -destination id=6C41B609-DA05-4FAD-98F3-CC0264871189
User defaults from command line:
IDEPackageSupportUseBuiltinSCM = YES
note: Using new build system
note: Planning
Analyze workspace
Create build description
Build description signature: 1552deb311feffa24b258a2f780d63f1
Build description path: /Users/younisrahman/Library/Developer/Xcode/DerivedData/Ajman-gmdogtmpvnnzkcfzhirvzdbwaslh/Build/Intermediates.noindex/XCBuildData/1552deb311feffa24b258a2f780d63f1-desc.xcbuild
note: Build preparation complete
note: Building targets in parallel
CompileC /Users/younisrahman/Library/Developer/Xcode/DerivedData/Ajman-gmdogtmpvnnzkcfzhirvzdbwaslh/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/ReactCommon.build/Objects-normal/x86_64/RCTTurboModuleManager.o /Volumes/Software/Projects/React-Native/Ajman/node_modules/react-native/ReactCommon/turbomodule/core/platform/ios/RCTTurboModuleManager.mm normal x86_64 objective-c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'ReactCommon' from project 'Pods')
cd /Volumes/Software/Projects/React-Native/Ajman/ios/Pods
export LANG\=en_US.US-ASCII
.
.
.
.
.
The following build commands failed:
CompileC /Users/younisrahman/Library/Developer/Xcode/DerivedData/Ajman-gmdogtmpvnnzkcfzhirvzdbwaslh/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/ReactCommon.build/Objects-normal/x86_64/RCTTurboModuleManager.o /Volumes/Software/Projects/React-Native/Ajman/node_modules/react-native/ReactCommon/turbomodule/core/platform/ios/RCTTurboModuleManager.mm normal x86_64 objective-c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'ReactCommon' from project 'Pods')
(1 failure)
# Add this code bottom in Podfile
post_install do |installer|
#Fix after updating to Xcode 13.1
find_and_replace("../node_modules/react-native/React/CxxBridge/RCTCxxBridge.mm",
"_initializeModules:(NSArray<id<RCTBridgeModule>> *)modules", "_initializeModules:(NSArray<Class> *)modules")
find_and_replace("../node_modules/react-native/ReactCommon/turbomodule/core/platform/ios/RCTTurboModuleManager.mm",
"RCTBridgeModuleNameForClass(module))", "RCTBridgeModuleNameForClass(Class(module)))")
end
def find_and_replace(dir, findstr, replacestr)
Dir[dir].each do |name|
text = File.read(name)
replace = text.gsub(findstr,replacestr)
if text != replace
puts "Fix: " + name
File.open(name, "w") { |file| file.puts replace }
STDOUT.flush
end
end
Dir[dir + '*/'].each(&method(:find_and_replace))
end
# If not work try this
change a parameter cast in the React module RCTTurboModuleManager.mm,
RCTBridgeModuleNameForClass(strongModule))
to
RCTBridgeModuleNameForClass(Class(strongModule)))

Installing Node.JS on Centos 5.5

I'm trying to install Node.js on Centos 5.5, which the latest update has removed yum.
So when i'm trying to run make I get the following error. Any ideas why, or what is going on?
make -C out BUILDTYPE=Release V=1
make[1]: Entering directory `/usr/local/src/node-v0.12.0/out'
LD_LIBRARY_PATH=/usr/local/src/node-v0.12.0/out/Release/lib.host:/usr/local/src/node-v0.12.0/out/Release/lib.target:$LD_LIBRARY_PATH; export LD_LIBRARY_PATH; cd ../deps/v8/tools/gyp; mkdir -p /usr/local/src/node-v0.12.0/out/Release/obj/gen; python ../../tools/js2c.py "/usr/local/src/node-v0.12.0/out/Release/obj/gen/libraries.cc" CORE off ../../src/runtime.js ../../src/v8natives.js ../../src/symbol.js ../../src/array.js ../../src/string.js ../../src/uri.js ../../third_party/fdlibm/fdlibm.js ../../src/math.js ../../src/messages.js ../../src/apinatives.js ../../src/debug-debugger.js ../../src/mirror-debugger.js ../../src/liveedit-debugger.js ../../src/date.js ../../src/json.js ../../src/regexp.js ../../src/arraybuffer.js ../../src/typedarray.js ../../src/weak_collection.js ../../src/promise.js ../../src/object-observe.js ../../src/collection.js ../../src/collection-iterator.js ../../src/macros.py ../../src/array-iterator.js ../../src/string-iterator.js
File "../../tools/js2c.py", line 409
except Error as e:
^
SyntaxError: invalid syntax
make[1]: *** [/usr/local/src/node-v0.12.0/out/Release/obj/gen/libraries.cc] Error 1
make[1]: Leaving directory `/usr/local/src/node-v0.12.0/out'
make: *** [node] Error 2
I'm encountering the same issue on RHEL5. I found a work-around until this gets fixed upstream. Edit deps/v8/tools/gyp/v8.gyp and replace 'python' with 'python2.7' to force that stage of the compile to use the correct version of python.
I filed an upstream bug at https://github.com/joyent/node/issues/9217

Gulp-Coveralls returns 422, no TravisCI builds can be found

TravisCI builds are passing for my open-source project, and I'm now trying to integrate gulp-coveralls. On Coveralls.io, no builds can be found for my repository, even though Travis builds have run successfully since I added my repo to Coveralls.
'There have been no builds for this repo.'
When I try to run my gulp-coveralls gulp task, I get this error:
'Repo token could not be determined. Continuing without it.'
Error in plugin 'gulp-coveralls'
Bad response:422 {"message":"Couldn't find a repository matching this job.","error":true}
at handleError (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/index.js:11:30)
at sendToCoverallsCallback (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/index.js:19:9)
at /Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/index.js:31:13
at Request._callback (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/node_modules/coveralls/lib/sendToCoveralls.js:7:5)
at Request.self.callback (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/node_modules/coveralls/node_modules/request/index.js:142:22)
at Request.EventEmitter.emit (events.js:98:17)
at Request.<anonymous> (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/node_modules/coveralls/node_modules/request/index.js:856:14)
at Request.EventEmitter.emit (events.js:117:20)
at IncomingMessage.<anonymous> (/Users/sarah.green/angular-embedly/node_modules/gulp-coveralls/node_modules/coveralls/node_modules/request/index.js:808:12)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:919:16
at process._tickCallback (node.js:419:13)
Here's what I've got so far:
gulp-coveralls in my dev dependencies in package.json
gulpfile.js:
var coveralls = require('gulp-coveralls');
...
gulp.task('coveralls', function () {
gulp.src('coverage/**/lcov.info')
.pipe(coveralls());
});
karma.conf.js:
coverageReporter: {
type : 'lcov',
dir : 'coverage/'
}
Github: https://github.com/lithiumtech/angular-embedly
I use Karma and PhantomJS to run my tests. The file coverage/lcov.info is definitely being generated. Any idea what could be going on?
Sarah,
What you are missing is a coveralls repository token. You must go to coveralls.io and create a login using your GitHub account. This will then pull all your repos into coveralls. Then for the repo that you want to use coveralls with, you turn coveralls on by clicking the "Off" switch.
Now click the "view on coveralls" button and it will show you your repo key. You can then set it up by creating a .coveralls.yml file and copying your keys into that file. This should solve your problem.
Maybe you have a mistake in your .coveralls.yml file. If you are using Travis CI, try this:
service_name: travis-ci
repo_token: token_given
and if you're using Travis Pro:
service_name: travis-pro
repo_token: token_given
I hope this will be useful.
For GitHub builds running in travis-ci.org you don't need a service name in your .coveralls.yml file, just the token. You don't need a passing build in Travis either, just successfully generated LCOV data and a plugin that sends it.
I had one issue with gulp-coveralls where the LCOV data was not sent properly to coveralls, when read from file using gulp.src. The only way I it would work finally was if the LCOV data was sent to the plugin directly, rather than using an intermediary file to store it to first.
To have both LCOV data piped to gulp-coveralls and have a JSON/HTML report, finally I resorted to lazy-pipe to create reusable steps.
The complete project can be found at GitHub's angular-logger
// .coveralls.yml
repo_token: the_token
var jasmine = require('gulp-jasmine');
var cover = require('gulp-coverage');
var coveralls = require('gulp-coveralls');
var lazypipe = require('lazypipe');
(..)
// gulpfile.js
var testAndGather = lazypipe()
.pipe(cover.instrument, {
pattern: ['src/**/*.js'],
debugDirectory: 'debug'
})
.pipe(jasmine, {includeStackTrace: true})
.pipe(cover.gather);
gulp.task('test', ['build'], function () {
gulp.src('spec/**/*spec.js')
.pipe(testAndGather())
.pipe(cover.format(['html']))
.pipe(gulp.dest('reports'));
});
gulp.task('travis', ['build'], function () {
gulp.src('spec/**/*spec.js')
.pipe(testAndGather())
.pipe(cover.format(['lcov']))
.pipe(coveralls()); // directly pipe into coveralls
});
Using:
"gulp-jasmine": "~2.0.1",
"gulp-coverage": "~0.3.35",
"gulp-coveralls": "~0.1.4",
"lazypipe": "~0.2.3"

How to auto-reload files in Node.js?

Any ideas on how I could implement an auto-reload of files in Node.js? I'm tired of restarting the server every time I change a file.
Apparently Node.js' require() function does not reload files if they already have been required, so I need to do something like this:
var sys = require('sys'),
http = require('http'),
posix = require('posix'),
json = require('./json');
var script_name = '/some/path/to/app.js';
this.app = require('./app').app;
process.watchFile(script_name, function(curr, prev){
posix.cat(script_name).addCallback(function(content){
process.compile( content, script_name );
});
});
http.createServer(this.app).listen( 8080 );
And in the app.js file I have:
var file = require('./file');
this.app = function(req, res) {
file.serveFile( req, res, 'file.js');
}
But this also isn't working - I get an error in the process.compile() statement saying that 'require' is not defined. process.compile is evaling the app.js, but has no clue about the node.js globals.
A good, up to date alternative to supervisor is nodemon:
Monitor for any changes in your node.js application and automatically restart the server - perfect for development
To use nodemon with version of Node without npx (v8.1 and below, not advised):
$ npm install nodemon -g
$ nodemon app.js
Or to use nodemon with versions of Node with npx bundled in (v8.2+):
$ npm install nodemon
$ npx nodemon app.js
Or as devDependency in with an npm script in package.json:
"scripts": {
"start": "nodemon app.js"
},
"devDependencies": {
"nodemon": "..."
}
node-supervisor is awesome
usage to restart on save for old Node versions (not advised):
npm install supervisor -g
supervisor app.js
usage to restart on save for Node versions that come with npx:
npm install supervisor
npx supervisor app.js
or directly call supervisor in an npm script:
"scripts": {
"start": "supervisor app.js"
}
i found a simple way:
delete require.cache['/home/shimin/test2.js']
If somebody still comes to this question and wants to solve it using only the standard modules I made a simple example:
var process = require('process');
var cp = require('child_process');
var fs = require('fs');
var server = cp.fork('server.js');
console.log('Server started');
fs.watchFile('server.js', function (event, filename) {
server.kill();
console.log('Server stopped');
server = cp.fork('server.js');
console.log('Server started');
});
process.on('SIGINT', function () {
server.kill();
fs.unwatchFile('server.js');
process.exit();
});
This example is only for one file (server.js), but can be adapted to multiple files using an array of files, a for loop to get all file names, or by watching a directory:
fs.watch('./', function (event, filename) { // sub directory changes are not seen
console.log(`restart server`);
server.kill();
server = cp.fork('server.js');
})
This code was made for Node.js 0.8 API, it is not adapted for some specific needs but will work in some simple apps.
UPDATE:
This functional is implemented in my module simpleR, GitHub repo
nodemon came up first in a google search, and it seems to do the trick:
npm install nodemon -g
cd whatever_dir_holds_my_app
nodemon app.js
nodemon is a great one. I just add more parameters for debugging and watching options.
package.json
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon --watch server --inspect ./server/server.js"
}
The command: nodemon --watch server --inspect ./server/server.js
Whereas:
--watch server Restart the app when changing .js, .mjs, .coffee, .litcoffee, and .json files in the server folder (included subfolders).
--inspect Enable remote debug.
./server/server.js The entry point.
Then add the following config to launch.json (VS Code) and start debugging anytime.
{
"type": "node",
"request": "attach",
"name": "Attach",
"protocol": "inspector",
"port": 9229
}
Note that it's better to install nodemon as dev dependency of project. So your team members don't need to install it or remember the command arguments, they just npm run dev and start hacking.
See more on nodemon docs: https://github.com/remy/nodemon#monitoring-multiple-directories
Nodemon has been the go to for restarting server for file changes for long time. Now with Node.js 19 they have introduced a --watch flag, which does the same [experimental]. Docs
node --watch index.js
node-dev works great. npm install node-dev
It even gives a desktop notification when the server is reloaded and will give success or errors on the message.
start your app on command line with:
node-dev app.js
There is Node-Supervisor that you can install by
npm install supervisor
see http://github.com/isaacs/node-supervisor
You can use nodemon from NPM.
And if you are using Express generator then you can using this command inside your project folder:
nodemon npm start
or using Debug mode
DEBUG=yourapp:* nodemon npm start
you can also run directly
nodemon your-app-file.js
Hope this help.
There was a recent (2009) thread about this subject on the node.js mailing list. The short answer is no, it's currently not possible auto-reload required files, but several people have developed patches that add this feature.
With Node.js 19 you can monitor file changes with the --watch option. After a file is changed, the process is restarted automatically, reflecting new changes.
node --watch server.js
yet another solution for this problem is using forever
Another useful capability of Forever is that it can optionally restart
your application when any source files have changed. This frees you
from having to manually restart each time you add a feature or fix a
bug. To start Forever in this mode, use the -w flag:
forever -w start server.js
Here is a blog post about Hot Reloading for Node. It provides a github Node branch that you can use to replace your installation of Node to enable Hot Reloading.
From the blog:
var requestHandler = require('./myRequestHandler');
process.watchFile('./myRequestHandler', function () {
module.unCacheModule('./myRequestHandler');
requestHandler = require('./myRequestHandler');
}
var reqHandlerClosure = function (req, res) {
requestHandler.handle(req, res);
}
http.createServer(reqHandlerClosure).listen(8000);
Now, any time you modify myRequestHandler.js, the above code will no­tice and re­place the local re­questHandler with the new code. Any ex­ist­ing re­quests will con­tin­ue to use the old code, while any new in­com­ing re­quests will use the new code. All with­out shut­ting down the serv­er, bounc­ing any re­quests, pre­ma­ture­ly killing any re­quests, or even re­ly­ing on an in­tel­li­gent load bal­ancer.
I am working on making a rather tiny node "thing" that is able to load/unload modules at-will (so, i.e. you could be able to restart part of your application without bringing the whole app down).
I am incorporating a (very stupid) dependency management, so that if you want to stop a module, all the modules that depends on that will be stopped too.
So far so good, but then I stumbled into the issue of how to reload a module. Apparently, one could just remove the module from the "require" cache and have the job done. Since I'm not keen to change directly the node source code, I came up with a very hacky-hack that is: search in the stack trace the last call to the "require" function, grab a reference to it's "cache" field and..well, delete the reference to the node:
var args = arguments
while(!args['1'] || !args['1'].cache) {
args = args.callee.caller.arguments
}
var cache = args['1'].cache
util.log('remove cache ' + moduleFullpathAndExt)
delete( cache[ moduleFullpathAndExt ] )
Even easier, actually:
var deleteCache = function(moduleFullpathAndExt) {
delete( require.cache[ moduleFullpathAndExt ] )
}
Apparently, this works just fine. I have absolutely no idea of what that arguments["1"] means, but it's doing its job. I believe that the node guys will implement a reload facility someday, so I guess that for now this solution is acceptable too.
(btw. my "thing" will be here: https://github.com/cheng81/wirez , go there in a couple of weeks and you should see what I'm talking about)
solution at:
http://github.com/shimondoodkin/node-hot-reload
notice that you have to take care by yourself of the references used.
that means if you did : var x=require('foo'); y=x;z=x.bar; and hot reloaded
it.
it means you have to replace the references stored in x, y and z. in the hot reaload callback function.
some people confuse hot reload with auto restart
my nodejs-autorestart module also has upstart integration to enable auto start on boot.
if you have a small app auto restart is fine, but when you have a large app hot reload is more suitable. simply because hot reload is faster.
Also I like my node-inflow module.
Here's a low tech method for use in Windows. Put this in a batch file called serve.bat:
#echo off
:serve
start /wait node.exe %*
goto :serve
Now instead of running node app.js from your cmd shell, run serve app.js.
This will open a new shell window running the server. The batch file will block (because of the /wait) until you close the shell window, at which point the original cmd shell will ask "Terminate batch job (Y/N)?" If you answer "N" then the server will be relaunched.
Each time you want to restart the server, close the server window and answer "N" in the cmd shell.
my app structure:
NodeAPP (folder)
|-- app (folder)
|-- all other file is here
|-- node_modules (folder)
|-- package.json
|-- server.js (my server file)
first install reload with this command:
npm install [-g] [--save-dev] reload
then change package.json:
"scripts": {
"start": "nodemon -e css,ejs,js,json --watch app"
}
now you must use reload in your server file:
var express = require('express');
var reload = require('reload');
var app = express();
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log( 'server is running on port ' + app.get('port'));
});
reload(server, app);
and for last change, end of your response send this script:
<script src="/reload/reload.js"></script>
now start your app with this code:
npm start
You can do it with browser-refresh. Your node app restarts automatically, your result page in browser also refreshes automatically. Downside is that you have to put js snippet on generated page. Here's the repo for the working example.
const http = require('http');
const hostname = 'localhost';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
res.write('Simple refresh!');
res.write(`<script src=${process.env.BROWSER_REFRESH_URL}></script>`);
res.end();
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
if (process.send) {
process.send({ event: 'online', url: `http://${hostname}:${port}/` })
}
});
Not necessary to use nodemon or other tools like that. Just use capabilities of your IDE.
Probably best one is IntelliJ WebStorm with hot reload feature (automatic server and browser reload) for node.js.
I have tried pm2 : installation is easy and easy to use too; the result is satisfying. However, we have to take care of which edition of pm2 that we want. pm 2 runtime is the free edition, whereas pm2 plus and pm2 enterprise are not free.
As for Strongloop, my installation failed or was not complete, so I couldn't use it.
If your talking about server side NodeJS hot-reloading, lets say you wish to have an Javascript file on the server which has an express route described and you want this Javascript file to hot reload rather than the server re-starting on file change then razzle can do that.
An example of this is basic-server
https://github.com/jaredpalmer/razzle/tree/master/examples/basic-server
The file https://github.com/jaredpalmer/razzle/blob/master/examples/basic-server/src/server.js will hot-reload if it is changed and saved, the server does not re-start.
This means you can program a REST server which can hot-reload using this razzle.
it's quite simple to just do this yourself without any dependency... the built in file watcher have matured enough that it dose not sucks as much as before
you don't need any complicated child process to spawn/kill & pipe std to in/out... you just need a simple web worker, that's all! A web Worker is also what i would have used in browsers too... so stick to web techniques! worker will also log to the console
import { watch } from 'node:fs/promises'
import { Worker } from 'node:worker_threads'
let worker = new Worker('./app.js')
async function reloadOnChange (dir) {
const watcher = watch(dir, { recursive: true })
for await (const change of watcher) {
if (change.filename.endsWith('.js')) {
worker.terminate()
worker = new Worker('./app.js')
}
}
}
// All the folder to watch for
['./src', './lib', './test'].map(reloadOnChange)
this might not be the best solution where you use anything else other than javascript and do not depend on some build process.
Use this:
function reload_config(file) {
if (!(this instanceof reload_config))
return new reload_config(file);
var self = this;
self.path = path.resolve(file);
fs.watchFile(file, function(curr, prev) {
delete require.cache[self.path];
_.extend(self, require(file));
});
_.extend(self, require(file));
}
All you have to do now is:
var config = reload_config("./config");
And config will automatically get reloaded :)
loaddir is my solution for quick loading of a directory, recursively.
can return
{ 'path/to/file': 'fileContents...' }
or
{ path: { to: { file: 'fileContents'} } }
It has callback which will be called when the file is changed.
It handles situations where files are large enough that watch gets called before they're done writing.
I've been using it in projects for a year or so, and just recently added promises to it.
Help me battle test it!
https://github.com/danschumann/loaddir
You can use auto-reload to reload the module without shutdown the server.
install
npm install auto-reload
example
data.json
{ "name" : "Alan" }
test.js
var fs = require('fs');
var reload = require('auto-reload');
var data = reload('./data', 3000); // reload every 3 secs
// print data every sec
setInterval(function() {
console.log(data);
}, 1000);
// update data.json every 3 secs
setInterval(function() {
var data = '{ "name":"' + Math.random() + '" }';
fs.writeFile('./data.json', data);
}, 3000);
Result:
{ name: 'Alan' }
{ name: 'Alan' }
{ name: 'Alan' }
{ name: 'Alan' }
{ name: 'Alan' }
{ name: '0.8272748321760446' }
{ name: '0.8272748321760446' }
{ name: '0.8272748321760446' }
{ name: '0.07935990858823061' }
{ name: '0.07935990858823061' }
{ name: '0.07935990858823061' }
{ name: '0.20851597073487937' }
{ name: '0.20851597073487937' }
{ name: '0.20851597073487937' }
another simple solution is to use fs.readFile instead of using require
you can save a text file contaning a json object, and create a interval on the server to reload this object.
pros:
no need to use external libs
relevant for production (reloading config file on change)
easy to implement
cons:
you can't reload a module - just a json containing key-value data
For people using Vagrant and PHPStorm, file watcher is a faster approach
disable immediate sync of the files so you run the command only on save then create a scope for the *.js files and working directories and add this command
vagrant ssh -c "/var/www/gadelkareem.com/forever.sh restart"
where forever.sh is like
#!/bin/bash
cd /var/www/gadelkareem.com/ && forever $1 -l /var/www/gadelkareem.com/.tmp/log/forever.log -a app.js
I recently came to this question because the usual suspects were not working with linked packages. If you're like me and are taking advantage of npm link during development to effectively work on a project that is made up of many packages, it's important that changes that occur in dependencies trigger a reload as well.
After having tried node-mon and pm2, even following their instructions for additionally watching the node_modules folder, they still did not pick up changes. Although there are some custom solutions in the answers here, for something like this, a separate package is cleaner. I came across node-dev today and it works perfectly without any options or configuration.
From the Readme:
In contrast to tools like supervisor or nodemon it doesn't scan the filesystem for files to be watched. Instead it hooks into Node's require() function to watch only the files that have been actually required.
const cleanCache = (moduleId) => {
const module = require.cache[moduleId];
if (!module) {
return;
}
// 1. clean parent
if (module.parent) {
module.parent.children.splice(module.parent.children.indexOf(module), 1);
}
// 2. clean self
require.cache[moduleId] = null;
};

Categories