I am new on javascript and I am trying to automate download of files from sharepoint with nodejs. The code is the following one:
const { sppull } = require("sppull");
const context = {
siteUrl: "xxx",
creds: {
username: "xxx",
password: "xxx"
}
};
const options = {
spRootFolder: "Shared%20Documents/SSC%20Projection/ZIP",
dlRootFolder: "W:\\SCM\\RawData\\SSC_Proj"
};
sppull(context, options)
.then((downloadResults) => {
console.log("Files are downloaded");
console.log("For more, please check the results", JSON.stringify(downloadResults));
})
.catch((err) => {
console.log("Core error has happened", err);
});
However,the engine is showing the following error message:
Folders proceeding: 0 out of 0 [recursive scanning...]
Error in getFolderContent: Cannot read property 'Folders' of undefined
Core error has happened Cannot read property 'Folders' of undefined
Process finished with exit code 0
Related
Code:
const context = {
siteUrl: 'https://<tenant>.sharepoint.com',
creds: {
username: "<username>#<tenant>.onmicrosoft.com",
password: "***",
online: true
}
};
const options2 = {
spRootFolder: "Shared%20Documents/docverify",
dlRootFolder: "./docverify"
};
SPPull.download(context, options2)
.then((downloadResults) => {
console.log("Files are downloaded", downloadResults);
console.log("For more, please check the results", JSON.stringify(downloadResults));
})
.catch((err) => {
console.log("Core error has happened", err);
});
Output:
Files are downloaded []
For more please check the results []
Attached screenshot of the file in sharepoint
enter image description here
Files to be downloaded
I am writing a web app with fastify in typescript. I have generated the project using fastify-cli.
fastify generate --lang=ts try-fastify-typescript
I have used #sinclair/typebox for schema validation. But I am getting the below error when running the app npm start.
FastifyError [Error]: Failed building the validation schema for POST:
/user, due to error strict mode: unknown keyword: "kind"
at Boot. (/Volumes/Segate Backup Plus Drive/projects/javascript/try-fastify-typescript/node_modules/fastify/lib/route.js:309:21)
at Object.onceWrapper (events.js:519:28)
at Boot.emit (events.js:412:35)
at /Volumes/Segate Backup Plus Drive/projects/javascript/try-fastify-typescript/node_modules/avvio/boot.js:160:12
at /Volumes/Segate Backup Plus Drive/projects/javascript/try-fastify-typescript/node_modules/avvio/plugin.js:276:7
at done (/Volumes/Segate Backup Plus Drive/projects/javascript/try-fastify-typescript/node_modules/avvio/plugin.js:201:5)
at check (/Volumes/Segate Backup Plus Drive/projects/javascript/try-fastify-typescript/node_modules/avvio/plugin.js:225:9)
at internal/process/task_queues.js:141:7
at AsyncResource.runInAsyncScope (async_hooks.js:197:9)
at AsyncResource.runMicrotask (internal/process/task_queues.js:138:8) { code:
'FST_ERR_SCH_VALIDATION_BUILD', statusCode: 500 }
Below is my code.
import { FastifyPluginAsync, RouteShorthandOptions } from 'fastify';
import { Static, Type } from '#sinclair/typebox';
const User = Type.Object({
name: Type.String(),
mail: Type.Optional(Type.String({ format: "email" })),
});
type UserType = Static<typeof User>;
const reqOpts: RouteShorthandOptions = {
schema: {
body: User
}
};
interface GetUserRequest {
Body: UserType,
Reply: UserType
}
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.get('/', async function (request, reply) {
return { root: true }
});
fastify.post<GetUserRequest>('/user', reqOpts, async(request, reply)=> {
request.log.info("User Name: " + request.body.name);
request.log.info("User Mail: " + request.body.mail);
return {...request.body};
});
}
export default root;
Adding the full code repository here.
I'm trying to send an email using Mailgun's npm client - Mailgun.js.
When sending in development mode, everything works correctly. But when I upload the Node server to Cloud Run, something breaks.
Here is the code in the sendEmail helper file:
import formData from 'form-data';
import Mailgun from 'mailgun.js';
const sendEmail = async ({ to, subject, text, attachment, scheduledDate }) => {
const mailgun = new Mailgun(formData);
const mg = mailgun.client({
username: 'api',
key: process.env.MAILGUN_KEY,
url: 'https://api.eu.mailgun.net'
});
const data = {
from: `<myemail#mydomain.com>`,
to,
subject,
text
};
if (attachment) {
data.attachment = attachment;
}
if (scheduledDate) {
data['o:deliverytime'] = new Date(scheduledDate).toUTCString();
}
try {
const result = await mg.messages.create(process.env.MAILGUN_DOMAIN, data);
if (result.status && result.status !== 200) {
throw ({ code: result.status, message: result.message });
}
return true;
} catch(err) {
console.log(err);
return { error: err };
}
};
export default sendEmail;
And then in another file:
import { Router } from 'express';
import generateInvoicePDF from '../helpers/generateInvoicePDF.js';
import sendEmail from '../helpers/sendEmail.js';
const router = Router();
router.post('/email', async (req, res, next) => {
try {
const file = await generateInvoicePDF(invoice);
if (file?.error) {
throw ({ code: pdf.error.code, message: pdf.error.message });
}
const email = await sendEmail({
to: 'testemail#example.com',
subject: 'Invoice',
text: 'Test',
attachment: { filename: 'Invoice', data: file }
});
if (email?.error) {
throw ({ code: email.error.code, message: email.error.message });
}
res.status(200).json({ success: true });
} catch(err) {
next(err);
}
});
export default router;
The error I get when in production mode in Cloud Run's logs is:
TypeError: fetch failed
at Object.processResponse (node:internal/deps/undici/undici:5575:34)
at node:internal/deps/undici/undici:5901:42
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) {
cause: TypeError: object2 is not iterable
at action (node:internal/deps/undici/undici:1661:39)
at action.next (<anonymous>)
at Object.pull (node:internal/deps/undici/undici:1709:52)
at ensureIsPromise (node:internal/webstreams/util:172:19)
at readableStreamDefaultControllerCallPullIfNeeded (node:internal/webstreams/readablestream:1884:5)
at node:internal/webstreams/readablestream:1974:7
}
Why the hell does it work in development mode on my local machine, but not when uploaded to Cloud Run?
For anyone struggling with something similar - I eventually figured out the problem.
On my local machine, where everything was working as expected, I'm using Node v16.15.0, whereas in the Dockerfile, I had specified
FROM node:latest
and therefore Cloud Run was using a newer version, which led to the problems...
I've now deployed using version 16.15.0 and everything works fine
I successfully installed and loaded kuzzle-device-manager in the backend file:
import { Backend } from 'kuzzle';
import { DeviceManagerPlugin } from 'kuzzle-device-manager';
const app = new Backend('playground');
console.log(app.config);
const deviceManager = new DeviceManagerPlugin();
const mappings = {
updatedAt: { type: 'date' },
payloadUuid: { type: 'keyword' },
value: { type: 'float' }
}
deviceManager.devices.registerMeasure('humidity', mappings)
app.plugin.use(deviceManager)
app.start()
.then(async () => {
// Interact with Kuzzle API to create a new index if it does not already exist
console.log(' started!');
})
.catch(console.error);
But when i try to use controllers from that plugin for example device-manager/device with create action i get an error output.
Here is my "client" code in js:
const { Kuzzle, WebSocket } = require("kuzzle-sdk")
const kuzzle = new Kuzzle(
new WebSocket('KUZZLE_IP')
)
kuzzle.on('networkError', error => {
console.error('Network Error: ', error);
})
const run = async () => {
try {
// Connects to the Kuzzle server
await kuzzle.connect();
// Creates an index
const result = await kuzzle.query({
index: "nyc-open-data",
controller: "device-manager/device",
action: "create",
body: {
model: "model-1234",
reference: "reference-1234"
}
}, {
queuable: false
})
console.log(result)
} catch (error) {
console.error(error.message);
} finally {
kuzzle.disconnect();
}
};
run();
And the result log:
API action "device-manager/device":"create" not found
Note: The nyc-open-data index exists and is empty.
We apologize for this mistake in the documentation, the device-manager/device:create method is not available because the plugin is using auto-provisioning until the v2.
You should send a payload to your decoder, the plugin will automatically provision the device if it does not exists https://docs.kuzzle.io/official-plugins/device-manager/1/guides/decoders/#receive-payloads
Im tring to catch more details when error accuring.
when the error is accuring im using node api server to catch the error and save in log file.
i simulated a Network Error and tring to get many details as possible.
when i console.log the error in frontend im getting this:
withFormHandler.js:28 Uncaught Error: Error: Network Error
at Object.componentDidUpdate (withFormHandler.js:28)
...
but i cant send this information using my api.
all im getting in the server side is an empty object.
so how can i catch and send many details as possible about the error and write it to the log file?
this is my ErrorBoundry component:
class ErrorBoundary extends React.Component {
state = {
hasError: false,
error: { message: "", stack: "" },
info: { componentStack: "" },
};
static getDerivedStateFromError = (error) => {
return { hasError: true };
};
componentDidCatch = (error, info) => {
this.setState({ error, info });
axios
.get(`http://localhost:5001/api/logs/error`, {
params: {
error: error.message,
details: info,
// details:error ---> this is also not give me information i need
},
})
.catch(() => {});
};
render() {
const { hasError, error, info } = this.state;
const { children } = this.props;
return hasError ? <ErrorComponent message={error.message} /> : children;
}
}
this is the server side handle:
router.get("/error", (req, res) => {
const errorMessage = req.query.error;
const details = req.query.details; -----> return an empty object :(
const logFile = "./logs/debug.log";
if (errorMessage) {
let error = errorMessage + "\r\n" + details;
fs.appendFile(logFile, error, function (err) {
// callback or something
});
}
});