Update JSON file write not working in NodeJS - javascript

I'm trying to read existing JSON file and update the existing value and saving it back. I'm getting below error message:
node:internal/modules/cjs/loader:944
throw err;
^
Error: Cannot find module 'src/myApp/test.json'
Require stack:
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:941:15)
at Function.Module._load (node:internal/modules/cjs/loader:774:27)
at Module.require (node:internal/modules/cjs/loader:1013:19)
at require (node:internal/modules/cjs/helpers:93:18)
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
at Module.load (node:internal/modules/cjs/loader:989:32)
at Function.Module._load (node:internal/modules/cjs/loader:829:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) {
code: 'MODULE_NOT_FOUND',
}
Please find the code below -
Much appreciated if someone can help me to fix this issue.
test.json
{
"key": ""
}
updateJSON.js
const fs = require('fs');
const fileName = 'src/myApp/test.json';
const file = require(fileName);
file.key = "new value";
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
if (err) return console.log(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
});

The error message Error: Cannot find module 'src/myApp/test.json' indicates that the Node.js cannot resolve the src/myApp/test.json file correctly.
By default, the name(src/myApp/test.json here) not starting with ./ will be recognized as a module of Node.js and will be resolved from native modules and node_modules, which leads to the error.
Using a relative path like ../src/myApp/test.json should fix it.
Ref: https://nodejs.org/api/modules.html#modules_require_id

Related

Mindee API throws error- Error: Cannot find module 'node:buffer'

I was exploring Mindee to make a code that converts the pdf to text, so I followed the steps and used the code from the documentation, but when I run it with node it throws this error:
internal/modules/cjs/loader.js:883
throw err;
^
Error: Cannot find module 'node:buffer'
Require stack:
- C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\node_modules\mindee\src\inputs\sources.js
- C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\node_modules\mindee\src\inputs\index.js
- C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\node_modules\mindee\src\client.js
- C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\node_modules\mindee\src\index.js
- C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\app.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Users\budgi\OneDrive\Documentos\TrabajosBi\Proy\Fedex\v2\node_modules\mindee\src\inputs\sources.js:30:23)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\budgi\\OneDrive\\Documentos\\TrabajosBi\\Proy\\Fedex\\v2\\node_modules\\mindee\\src\\inputs\\sources.js',
'C:\\Users\\budgi\\OneDrive\\Documentos\\TrabajosBi\\Proy\\Fedex\\v2\\node_modules\\mindee\\src\\inputs\\index.js',
'C:\\Users\\budgi\\OneDrive\\Documentos\\TrabajosBi\\Proy\\Fedex\\v2\\node_modules\\mindee\\src\\client.js',
'C:\\Users\\budgi\\OneDrive\\Documentos\\TrabajosBi\\Proy\\Fedex\\v2\\node_modules\\mindee\\src\\index.js',
'C:\\Users\\budgi\\OneDrive\\Documentos\\TrabajosBi\\Proy\\Fedex\\v2\\app.js'
]
}
These are the folders:
folders
And the app.js (pasted the code from the documentation)
const mindee = require("mindee");
// for TS or modules:
// import * as mindee from "mindee";
// Init a new client
const mindeeClient = new mindee.Client({apiKey: "1234567890"});
// Load a file from disk and parse it
const invoiceResponse = mindeeClient
.docFromPath("/path/to/the/invoice.pdf")
.parse(mindee.InvoiceV3);
// Print a the parsed data
invoiceResponse.then((resp) => {
// The document property can be undefined:
// * TypeScript will throw an error without this guard clause
// (or consider using '?' notation)
// * JavaScript will be very happy to produce subtle bugs
// without this guard clause
if (resp.document === undefined) return;
// full object
console.log(resp.document);
// string summary
console.log(resp.document.toString());
});
What can be the cause of the error?

html-pdf: Failed to load PhantomJS module. Error: Cannot find module 'phantomjs-prebuilt'

I am using html-pdf NPM module to convert my html (bill.html) code to pdf file (bill.pdf), I have simple html with heading tag and exporting that html by fs module below
import { create } from 'html-pdf';
import fs from 'fs';
import path from 'path';
var html = fs.readFileSync(path.resolve(__dirname, "./bill.html"), 'utf8');
var options = { format: 'Letter' };
create(html, options).toFile('./bill.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res);
});
And I am getting this error of 'phantomjs-prebuilt'
html-pdf: Failed to load PhantomJS module. Error: Cannot find module 'phantomjs-prebuilt'
Require stack:
- /home/hardy/Documents/personal/api/node_modules/html-pdf/lib/pdf.js
- /home/hardy/Documents/personal/api/node_modules/html-pdf/lib/index.js
- /home/hardy/Documents/personal/api/src/app.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/hardy/Documents/personal/api/node_modules/html-pdf/lib/pdf.js:7:19)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Object.require.extensions.<computed> [as .js] (/home/hardy/Documents/personal/api/node_modules/babel-register/lib/node.js:152:7)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/home/hardy/Documents/personal/api/node_modules/html-pdf/lib/pdf.js',
'/home/hardy/Documents/personal/api/node_modules/html-pdf/lib/index.js',
'/home/hardy/Documents/personal/api/src/app.js'
]
}
Debugger listening on ws://127.0.0.1:5858/508c0ea9-c495-4254-9b05-cd2fd3cd8ae3
For help, see: https://nodejs.org/en/docs/inspector
assert.js:374
throw err;
^
AssertionError [ERR_ASSERTION] [ERR_ASSERTION]: html-pdf: Failed to load PhantomJS module. You have to set the path to the PhantomJS binary using 'options.phantomPath'
at new PDF (/home/hardy/Documents/personal/api/node_modules/html-pdf/lib/pdf.js:38:3)
at createPdf (/home/hardy/Documents/personal/api/node_modules/html-pdf/lib/index.js:10:14)
at Object.<anonymous> (/home/hardy/Documents/personal/api/src/app.js:8:1)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at loader (/home/hardy/Documents/personal/api/node_modules/babel-register/lib/node.js:144:5)
at Object.require.extensions.<computed> [as .js] (/home/hardy/Documents/personal/api/node_modules/babel-register/lib/node.js:154:7)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at Object.<anonymous> (/home/hardy/Documents/personal/api/node_modules/babel-cli/lib/_babel-node.js:154:22) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: undefined,
expected: true,
operator: '=='
}
Waiting for the debugger to disconnect...
As phantomjs-rebuilt is a deprecated
You can still install it forcefully and resolve the error.
Command - npm i phantomjs-prebuilt --force

Error: Cannot find module 'config' at Function.Module._resolveFilename

Hii I have simple node server, with the following structure
myapp
-config
-default-json
-index.js
-package-lock.json
-package.json
Here is my part of my index.js
'use strict';
const
config = require('config'),
express = require('express'),
request = require('request'),
body_parser = require('body-parser'),
app = express().use(body_parser.json()); // creates express http server
// Sets server port and logs message on success
app.listen(process.env.PORT || 1337, () => console.log('webhook is listening'));
when I run node index.js I get the following error
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module 'config'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (C:\xampp\htdocs\chat\index.js:13:14)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
what is wrong with my code?
I found solution by by installing config from npm
https://www.npmjs.com/package/config
follow the instruction above and it should work , it might help some one in future
You have to explicitly add the config module in your package.json:
"dependencies": {
"config": "version number"
}
https://www.npmjs.com/package/config
It means there is no config.js in your current location. Put the exact location of the config.js file..
Try,
config = require('./config/config'),

How to run jQuery in node.js [duplicate]

This question already has answers here:
Can I use jQuery with Node.js?
(21 answers)
Closed 4 years ago.
I have tried npm install jQuery --save and in my node file var $ = require('jquery'); but, then when I run my node file with
$.getJSON('https://en.wikipedia.org/wiki/Washington,_D.C.', function(data) {
//data is the JSON string
});
I get the error
TypeError: $.getJSON is not a function
at Object.<anonymous> (C:\Users\Karim\node 2\tweetPic.js:16:3)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I have also tried importing jquery using
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
});
which just returns
TypeError: require(...).env is not a function
at Object.<anonymous> (C:\Users\Karim\node 2\tweetPic.js:3:18)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I have installed the jsdom package in a similar fashion. Is there something wrong with my jquery code itself? How can I fix this?
Edit: It seems jQuery isn't really what I need here. I'm just going to look into a different way of retrieving json data.
Sorry but i don't know how to install jquery. But you apparently need it to request a website and fetch json. You could use request for that. Hope i helped you.
And you could do like :
request('https://en.wikipedia.org/wiki/Washington,_D.C.', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});

node.js cannot find 'neo4j' module (Thingdom)

After many tries, I am unnable to connect node.js to Neo4j installed in my computer. I am able to access both separately, and both work fine. I have install in my Node.js directory the Thingdom ('neo4j') module in the directory, but when require('neo4j') prints an error.
Image of my Node.js folder with Neo4j installed in modules
var neo4j = require("neo4j");
var db = new neo4j.GraphDatabase("http://localhost:7474");
var node = db.createNode({hello: 'world'}); // instantaneous, but...
node.save(function (err, node) { // ...this is what actually persists.
if (err) {
console.error('Error saving new node to database:', err);
} else {
console.log('Node saved to database with id:', node.id);
}
});
And when using in the cmd: "node index.js" it throws me this error:
C:\Users\RRamos\Documents\Projects\test-neo4j>node index.js
module.js:341
throw err;
^
Error: Cannot find module 'neo4j'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (C:\Users\RRamos\Documents\Projects\test-neo4j\index.js:1:75)
at Module._compile (module.js:413:34)
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)
I got the same problem. As there's no solution in this post, I just add mine.
After running $ npm init and $ npm install --save neo4j-driver, I copy and paste the neo4j example code in index.js:
var neo4j = require("neo4j");
var db = new neo4j.GraphDatabase('http://neo4j:<password>#localhost:7474');
And then I got the same error when running $ node index.js.
In my package.json, I found:
"dependencies": {
"neo4j-driver": "^1.1.0-M02"
}
It's neo4j-driver not neo4j. So replace it in index.js:
var neo4j = require("neo4j-driver");
var db = new neo4j.GraphDatabase('http://neo4j:<password>#localhost:7474');
Now you will get rid of the Cannot find module 'neo4j' error!
In addition, if you use the 1.1.0 version of neo4j-driver(for Neo4j 3.0.0+), you may get this error:
var db = new neo4j.GraphDatabase('http://neo4j:<password>#localhost:7474');
^
TypeError: neo4j.GraphDatabase is not a constructor
at Object.<anonymous> (D:\Codes\neo4j_test\server.js:2:10)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
at run (bootstrap_node.js:352:7)
at startup (bootstrap_node.js:144:9)
at bootstrap_node.js:467:3
It seems neo4j.GraphDatabase is only available in older version of neo4j-driver.
Here's the up-to-date tutorial of neo4j-driver.
Use the following code instead:
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "<password>"));
// Create a session to run Cypher statements in.
// Note: Always make sure to close sessions when you are done using them!
var session = driver.session();
// Run a Cypher statement, reading the result in a streaming manner as records arrive:
session
.run("MERGE (alice:Person {name : {nameParam} }) RETURN alice.name", { nameParam:'Alice' })
.subscribe({
onNext: function(record) {
console.log(record._fields);
},
onCompleted: function() {
// Completed!
session.close();
},
onError: function(error) {
console.log(error);
}
});

Categories

Resources