import express from 'express';
import db from 'sqlite'; // <=
import Promise from 'bluebird';
const app = express();
const port = process.env.PORT || 3000;
app.get('/posts', async (req, res, next) => {
try {
const posts = await db.all('SELECT * FROM Post LIMIT 10'); // <=
res.send(posts);
} catch (err) {
next(err);
}
});
Promise.resolve()
// First, try to open the database
.then(() => db.open('./database.sqlite', { Promise }) // <=
// Update db schema to the latest version using SQL-based migrations
.then(() => db.migrate({ force: 'last' }) // <=
// Display error message if something went wrong
.catch((err) => console.error(err.stack))
// Finally, launch the Node.js app
.finally(() => app.listen(port));
注意:上面的示例仅适用于Node.js v6 和更高版本(假设代码中使用import
的async/await
语言特性与Babel进行了转换)。对于早期版本的 Node.js,请使用var db = require('sqlite/legacy');
.