const creatUser = "INSERT INTO users(`firstname`,`lastname`,`email`,`password`) VALUES(?)";
const checkRegister = " SELECT * FROM users WHERE email = ? ";
So I have a big project include a lot of mysql query . And mysql package use string store query, Is there a way to handle multiple string in node js? like put them all into one file, I try the import fs package then read the file ,but it does a lot of job than I expect?
CodePudding user response:
I think you can still apply your idea to write all queries into one file, then use the fs
module to read them back.
Assuming that you have a file called queries.sql
with a semicolon ;
separator between the values:
const fs = require('fs');
const queries = fs.readFileSync('queries.sql', 'utf8')
.split(';')
.filter((query) => query.trim().length > 0);
console.log(queries); // ["SELECT * FROM users WHERE email = '[email protected]'", "INSERT INTO users(...) VALUES(...)"]
the rest should be simple :)
CodePudding user response:
I think you should just create a POJO (or multiple POJO's, grouping queries by something, like the purpose of the queries) object with the queries. Then you just require the file.
user-queries.js
module.exports = {
query1: "select * from users",
query2: "select * from users where id=?"
...
};
Then, whenever you need user queries, you just require the above.
const userQueries = require('./user-queries.js');
// Now you can do userQueries.query1, for example.
On in ES Modules
user-queries.js
export default {
query1: "select * from users",
query2: "select * from users where id=?"
...
};
Then:
import userQueries from './user-queries.js';
// Now you can do userQueries.query1, for example.