How to allow filesystem access - node-vm2

I want to provide filesystem access for use with fs. How can I grant the vm2 process access to a specific directory?
I've tried setting external to true and a root of /. The process is able to access the directory when run outside vm2.

Did you set builtin: ['fs']?
Try the below code sample
const {NodeVM} = require('vm2');
const vm = new NodeVM({
console: 'inherit',
sandbox: {},
require: {
external: true,
builtin: ['fs', 'path'],
root: "./",
mock: {
fs: {
readFileSync() { return 'Nice try!'; }
}
}
}
});

Related

TestCafe config setup for multiple environments

I'm wondering if it's possible to have a single .testcaferc.json file that provides config for all environments?
We've got a lot of config that's shared, so I don't really want to create individual config files for each environment if I don't have to.
Something like this would be great, but can't seem to see anything in the tc docs that mentions anything about environments
{
browsers: "chrome",
concurrency: 5,
baseUrl: "http://localhost:3000",
...
env: {
dev: {
baseUrl: "https://dev.example.com",
...
},
test: {
baseUrl: "https://test.example.com",
...
},
prod: {
baseUrl: "https://example.com",
...
},
}
}
Currently we pass a number of extra args into the scripts as below, which is getting really messy and difficult to maintain in our package file.
{
"test:e2e": "npm run test:cafe",
"test:e2e:dev": "npm run test:cafe -- --base-url=https://dev.example.com",
"test:e2e:test": "npm run test:cafe -- --base-url=https://test.example.com",
"test:e2e:prod": "npm run test:cafe -- --base-url=https://example.com","
}
Thanks!
You can use the JavaScript config file instead of a JSON config file. In this case, you can write your own logic right inside the config. For example, you can check the environment variable as follows:
.testcaferc.js:
module.exports = {
baseUrl: process.env.dev ? 'http://localhost:3000' : 'http://localhost:3005',
customActions: {},
}
Moreover, you can create different configuration files for different environments, and one for common settings. In this case, you can use the common settings from the common config file and import specific environment settings from other config files.
Common: .testcaferc.js
function resolveEnv () {
if (process.env.dev)
return './.testcaferc-dev.js'
else if (process.env.test)
return './.testcaferc-test.js'
else
return './.testcaferc-prod.js'
}
const commonConfig = {
skipJsErrors: true,
customActions: {}
}
const envConfigName = resolveEnv();
const envConfig = require(envConfigName);
module.exports = {
...commonConfig,
...envConfig,
}
.testcaferc-dev.js
module.exports = {
baseUrl: 'http://localhost:3000',
skipJsErrors: false,
}

Why Nuxt generate publicPath does not work as expected at first visit?

I'm using Nuxt v2.15.8 to create a static website using nuxt generate command. I expect the requests to the server for fetching the main js and CSS files to be made to / path, as I specified in my nuxt.cofig:
export default {
ssr: false,
target: 'static',
// ...
build: {
publicPath: process.env.NODE_ENV === 'development' ? '/_nuxt/' : '/',
},
// ...
}
When I visit the generated static website, despite what I specified in the build config, at first it tries to load data from /_nuxt/ path which does not exist. As you can see in the attached pictures, after getting a 404 error for this route, it loads data successfully from the correct path which is /, but it should not send those requests to /_nuxt path to begin with.
Request to the wrong path
Request to the correct path
Any idea about how can I eliminate those initial requests to /_nuxt/?
So I fixed the issue by adding the following lines to nuxt.config.js:
export default {
ssr: false,
target: 'static',
// ...
build: {
publicPath: process.env.NODE_ENV === 'development' ? '/_nuxt/' : '/',
},
// added the following lines
hooks: {
render: {
resourcesLoaded(resources) {
const path = `/`
resources.clientManifest && (resources.clientManifest.publicPath = path)
resources.modernManifest && (resources.modernManifest.publicPath = path)
resources.serverManifest && (resources.serverManifest.publicPath = path)
}
}
},
// ...
}

Setup of vue.config.js file to imitate production setup (connect two apps)

I run an R Shiny app on port 3000 which serves my vue.js App like this:
library(shiny)
server <- function(input, output, session) {
histogramData <- reactive({
mtcars
})
observe({
session$sendCustomMessage("histogramData", histogramData())
})
}
ui <- function() {
htmlTemplate("dist/index.html")
}
# Serve the bundle at js/main.js
if (dir.exists("dist/js")) {
addResourcePath("js", "dist/js")
}
# Serve the bundle at js/main.js
if (dir.exists("dist/css")) {
addResourcePath("css", "dist/css")
}
# Serve the bundle at js/main.js
if (dir.exists("dist/img")) {
addResourcePath("img", "dist/img")
}
shinyApp(ui, server)
For development, I would change it like this:
ui <- function() {
htmlTemplate("public/index.html")
}
However, I can not always run the build process just to connect the apps, I want to use the dev server to connect the apps and send data back and forth.
I have setup a vue.config.js with the following configuration to create a connection between the two apps.
const path = require('path')
module.exports = {
publicPath: ".",
devServer: {
port: 4000,
contentBase: path.resolve(__dirname, 'public'),
proxy: {
'/': {
target: 'http://localhost:3000'
},
'/websocket': {
target: 'ws://localhost:3000',
ws: true
}
}
},
transpileDependencies: [
"vuetify"
]
}
This was taken from a github repository, I am acutally quite clueless how to archieve this connection. My idea was to connect go on localhost:4000 and receive the data from localhost:3000, but nothing gets passed:
TypeError: Cannot read property 'addCustomMessageHandler' of undefined at VueComponent.mounted (HelloWorld.vue?140d:42)
This is based on the following method in my vue component (which works perfectly after the build process):
mounted: function () {
window.Shiny.addCustomMessageHandler('histogramData', histogramData =>
this.data.histogramData = histogramData
)
Can anyone tell me what´s wrong and help me to setup the connection correctly?

How can I fix nuxt js static site links leading to network error?

I have a very basic nuxt.js application using JSON in a local db.json file, for some reason the generated static site links leading to network error, but I can access them from the url or page refresh.
nuxt config
generate: {
routes () {
return axios.get('http://localhost:3000/projects')
.then((res) => {
return res.data.map((project) => {
return '/project/' + project.id
})
})
}
},
main root index page
data() {
return {
projects: []
}
},
async asyncData({$axios}){
let projects = await $axios.$get('http://localhost:3000/projects')
return {projects}
}
single project page
data() {
return {
id: this.$route.params.id
}
},
async asyncData({params, $axios}){
let project = await $axios.$get(`http://localhost:3000/projects/${params.id}`)
return {project}
}
P.S. I have edited the post with the code for the main and single project page
Issues with server-side requests of your application are caused by conflicts of ports on which app and json-server are running.
By default, both nuxt.js and json-server run on localhost:3000 and requests inside asyncData of the app sometimes do not reach correct endpoint to fetch projects.
Please, check fixed branch of your project's fork.
To ensure issue is easily debuggable, it is important to separate ports of API mock server and app itself for dev, generate and start commands.
Note updated lines in nuxt.config.js:
const baseURL = process.env.API_BASE_URL || 'http://localhost:3000'
export default {
server: {
port: 3001,
host: '0.0.0.0'
},
modules: [
['#nuxtjs/axios', {
baseURL
}]
],
generate: {
async routes () {
return axios.get(`${baseURL}/projects`)
.then((res) => {
return res.data.map((project) => {
return '/project/' + project.id
})
})
}
}
}
This ensures that API configuration is set from a single source and, ideally, comes from environmental variable API_BASE_URL.
Also, app's default port has been changed to 3001, to avoid conflict with json-server.
asyncData hooks have been updated accordingly to pass only necessary path for a request. Also, try..catch blocks are pretty much required for asyncData and fetch hooks, to handle error correctly and access error specifics.

What is the best approach to test a HapiJS plugin, with Lab?

What is the best way to test a HapiJS plugin, for example one plugin that add routes and handlers.
Since I have to create an instance of Hapi.Server to run the plugins, should I define all the tests from the app's root, for all the plugins ?
or
should I manage to get THE instance of Hapi.Server in my plugin's local tests ?
If I go for the second option, my server will have registered all the plugins, including those that the plugin to be tested doesn't depends on.
What is the best way to approach this ?
Thanks in advance.
If you're using Glue (and I highly recommend it), you can create a manifest variable for each test (or group of tests) you want to execute. The manifest only needs to include plugins required for that test to execute properly.
And expose some sort of init function to actually start your server. Small example:
import Lab = require("lab");
import Code = require('code');
import Path = require('path');
import Server = require('../path/to/init/server');
export const lab = Lab.script();
const it = lab.it;
const describe = lab.describe;
const config = {...};
const internals = {
manifest: {
connections: [
{
host: 'localhost',
port: 0
}
],
registrations: [
{
plugin: {
register: '../http_routes',
options: config
}
},
{
plugin: {
register: '../business_plugin',
options: config
}
}
]
},
composeOptions: {
relativeTo: 'some_path'
}
};
describe('business plugin', function () {
it('should do some business', function (done) {
Server.init(internals.manifest, internals.composeOptions, function (err, server) {
// run your tests here
});
});
});
init function:
export const init = function (manifest: any, composeOptions: any, next: (err?: any, server?: Hapi.Server) => void) {
Glue.compose(manifest, composeOptions, function (err: any, server: Hapi.Server) {
if (err) {
return next(err);
}
server.start(function (err: any) {
return next(err, server);
});
});
};