我基本上试图编写一个非常基本的程序,它将像这样工作:
Enter your name: _
Enter your age: _
Your name is <name> and your age is <age>.
Run Code Online (Sandbox Code Playgroud)
我一直试图弄清楚如何在Node中做这样的事情而不使用promptnpm模块.
我的尝试是:
import readline from 'readline'
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
rl.question('What is your name? ', (name) => {
rl.question('What is your age? ', (age) => {
console.log(`Your name is ${name} and your age is ${age}`)
})
})
Run Code Online (Sandbox Code Playgroud)
然而,这种嵌套的方式看起来很奇怪,无论如何我可以做到这一点,而不是像这样嵌套,以获得正确的顺序?
404.jade每当有无效的GET请求时,我都有一个我想要呈现的文件.
这是我目前的代码:
app.js
import Koa from 'koa'
import views from 'koa-views'
import serve from 'koa-static'
import rootRoutes from './routes/index'
import userRoutes from './routes/user'
const app = new Koa()
app.use(views(`${__dirname}/views`, { extension: 'jade' }))
app.use(serve(`${__dirname}/public`))
app.use(rootRoutes.routes())
app.use(userRoutes.routes())
app.listen(3000, () => {
console.log('Server running at http://localhost:3000')
})
export default app
Run Code Online (Sandbox Code Playgroud)
路线/ index.js
import Router from 'koa-router'
const router = new Router()
router.get('/', async ctx => {
await ctx.render('index')
})
router.get('/about', async ctx => {
await ctx.render('about')
})
export default router
Run Code Online (Sandbox Code Playgroud)
路线/ …
我有一个主秒表,每个步骤有4个迷你秒表.完成时间后,这里有一个定时器应该如何显示的示例:
MAIN: 00 : 14 : 57
-------------------
MINI1: 00 : 04 . 17
MINI2: 00 : 06 . 40
MINI3: 00 : 02 . 54
MINI4: 00 : 01 . 46
Run Code Online (Sandbox Code Playgroud)
迷你定时器应该与主定时器相加,就像在这种情况下一样.使用我当前的计时器,它似乎总是.02毫秒关闭,所以00 : 14 . 55在这种情况下它们会加起来而不是00 : 14 . 57.
这是我当前计时器的JSFiddle.我认为问题最有可能出现在stopwatch.js文件中,但我不确定为什么会这样,因为我Date.now()用来计算已经过了多少时间.这是一个stopwatch.js文件,它是单个秒表的代码:
class Stopwatch {
constructor (opts) {
this.isOn = false;
this.time = 0;
this.elem = opts.elem;
}
start () {
this.offset = Date.now();
this.interval = …Run Code Online (Sandbox Code Playgroud) 举个例子,假设我有一个类只有发出三种可能的事件- 'pending'或'success'或'failure'.此外,接收的参数类型eventHandler取决于发出的事件 -
'pending',eventHandler没有收到任何论据'success',eventHandler收到一个number'failure',eventHandler收到一个Error以下是我尝试建模的方法:
// @flow
import EventEmitter from 'events'
type CustomEventObj = {|
pending: void,
success: number,
error: Error
|}
declare class MyEventEmitter extends EventEmitter {
on<K: $Keys<CustomEventObj>>(
eventName: K,
eventHandler: (
e: $ElementType<CustomEventObj, K>,
...args: Array<any>
) => void
): this
}
Run Code Online (Sandbox Code Playgroud)
但是,这会导致如下错误:
Error ????????????????????????????????????????????????????????????????????????????????????????????????????? test.js:12:3
Cannot extend EventEmitter [1] with MyEventEmitter because an …Run Code Online (Sandbox Code Playgroud) 我正在从我的服务器向客户端发送PDF流,然后<object>在客户端的标签中显示该PDF .这是我的代码:
server.js
router.get('/pdf', function * () {
var stream = getMyFileStream();
this.set('Content-Type', 'application/pdf');
this.response.body = stream;
});
Run Code Online (Sandbox Code Playgroud)
client.js
var objectElement = document.querySelector('object');
fetch('/pdf', request)
.then(res => res.blob())
.then(blob => URL.createObjectURL(blob))
.then(url => {
objectElement.setAttribute('data', url)
objectElement.setAttribute('type', 'application/pdf')
})
Run Code Online (Sandbox Code Playgroud)
此代码似乎正常工作,但我在控制台中收到以下警告:
资源解释为Document但使用MIME类型application/pdf进行传输
为什么它认为我的资源应该是text/html?如果我将Content-Type标题更改为text/html,则会使警告消失但显然会导致PDF的呈现问题.任何帮助,将不胜感激.
这是我的文件:
.
??? app.js
??? res.cls
??? res.tex
Run Code Online (Sandbox Code Playgroud)
这是我的app.js文件的相关内容:
const { spawn } = require('child_process')
const latex = spawn('pdflatex', ['res.tex'])
Run Code Online (Sandbox Code Playgroud)
成功运行此代码会res.pdf在同一目录中创建一个文件.但是,我想将PDF作为流而不是创建文件,而是将其作为响应发送给浏览器.我试图避免在服务器中创建任何PDF文件,我只想立即将生成的PDF作为响应发送.是否可以更改此代码来执行此操作?
这是我的简单路线:
router.post('/getFile', async (ctx) => {
const fileName = `${ctx.request.body.file}.pdf`;
const file = fs.createReadStream(fileName); // This file might not exist.
file.on('error', (err) => {
ctx.response.status = 500; // This status code doesn't make it to client when there's an error.
});
ctx.response.type = 'application/pdf';
ctx.response.body = file;
});
Run Code Online (Sandbox Code Playgroud)
这是我的客户端代码:
async function main() {
const request = {
method: 'POST',
body: JSON.stringify({ file: 'bad-file-name' }),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/pdf'
}
};
const response = await fetch('/getFile', request);
if (!response.ok) …Run Code Online (Sandbox Code Playgroud) 我正试图从Koa中的POST请求处理程序触发下载koa-router.基本上,我正在尝试做这样的事情:
app.js
const Koa = require('koa')
const router = require('./router')
const app = new Koa()
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000)
Run Code Online (Sandbox Code Playgroud)
router.js
const fs = require('fs')
const Router = require('koa-router')
const router = new Router()
router.post('/generate', function * () {
const path = `${__dirname}/test.txt`
this.body = fs.createReadStream(path)
this.set('Content-disposition', 'attachment; filename= test.txt')
})
module.exports = router
Run Code Online (Sandbox Code Playgroud)
client.js
const { fetch } = window;
const request = {
method: 'POST',
body: JSON.stringify({ fake: 'data' })
}
// Make the POST request
fetch('/generate', request) …Run Code Online (Sandbox Code Playgroud) 我正在我的React/Redux应用程序中第一次尝试服务器端渲染.我现在遇到的一个问题是我需要初始状态来生成一个随机生成的字符串,然后将其作为prop传递给我的主要App组件.这显然是一个问题,因为它为客户端和服务器生成不同的字符串.我能做些什么来阻止这个问题的发生吗?
帮助理解的基本结构:
App.js
import React from 'react';
import { connect } from 'react-redux';
const App = ({ randomStr }) => (
<div>
<p>{randomStr}</p>
</div>
);
const mapStateToProps = (state) => ({
...
});
const mapDispatchToProp = (dispatch) => ({
...
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
Run Code Online (Sandbox Code Playgroud)
而我的减速机:
reducer.js
import { generateString } from '../util';
import { NEW_STRING } from '../constants';
const stringReducer = (state = generateString(), action) => {
switch (action.type) {
case NEW_STRING:
return generateString();
default: …Run Code Online (Sandbox Code Playgroud) javascript reactjs server-side-rendering react-dom react-dom-server
我的目标是检查类型,messages然后相应地将它们转换为字符串并添加它们.我怎样才能做到这一点?
public void addMessages(List<?> messages) {
if (messages != null) {
if (messages instanceof String) {
for (String message : messages) {
this.messages.add(message);
}
}
}
else {
for (Object message:messages) {
this.messages.add(String.valueOf(message));
}
}
}
Run Code Online (Sandbox Code Playgroud) javascript ×9
node.js ×5
koa ×3
koa-router ×2
ajax ×1
download ×1
ecmascript-6 ×1
eventemitter ×1
fetch ×1
flow-typed ×1
flowtype ×1
http ×1
java ×1
latex ×1
mime-types ×1
pdf ×1
pdflatex ×1
react-dom ×1
reactjs ×1
stopwatch ×1
timer ×1